Arrays (1D)
Arrays (2D)
Classes
Comments
File IO
Functions
Libraries
Loops
Operators
Parameters (const and reference)
Pointers
Program Structure
Selection (decisions)
Simple input/output
Struct
Variable declarations
const int MAX_ITEMS = 10; // common to use const for array size
double array[MAX_ITEMS]; // allocates space for 10 doubles
int count = 0; // you must maintain the count (may also be true in Java, if array not filled)
do {
cout << "Enter a double: ";
cin >> array[count];
count++; // count updated
char reply;
if (count < MAX_ITEMS)
{
cout << "More? ";
cin >> reply;
}
} while (count < MAX_ITEMS && reply == 'y');
// As in Java, index bounds are from 0 to size-1.
// A for-loop is often used to process all elements.
for (int i=0; i < count; i++)
cout << array[i] << endl;
// The following yields unpredictable results
cout << array[10] << endl;
final int MAX_ITEMS = 10;
// declare array, then allocate space (can be done on one line)
double[] array;
array = new double[MAX_ITEMS];
// The following displays 10
System.out.println("Array size is: " + array.length);
// The following causes an exception
System.out.println(array[10]);
int matrix[3][4];
// often processed with nested for loops
for (int row=0; row<3; row++)
for (int col=0; col<4; col++)
matrix[row][col] = 0;
ifstream infile; // ifstream used to read from fileCorresponding Java code:
ofstream outfile; // ofstream used to write to file
infile.open("numbers.dat"); // open makes connection to file on disk
if (!infile) // error checking
{
cout << "Error opening input file numbers.dat\n";
exit(1); // aborts program, requires cstdlib
}
outfile.open("numbers.out");
if (outfile.fail()) // another way to do error checking
{
cout << "Error opening output file numbers.out\n";
exit(1); // aborts program, requires cstdlib
}
double number;
infile >> number; // reads 1 floating point number from file, stops at white space
outfile << number; // writes 1 value to file
infile.close();
outfile.close();
double sqrt(double);The definition provides the body of the function. It consists of the header followed by the set of statements that perform the action of the function, surrounded by braces. For example:
void printArray(int numbers[], int size);
void printArray(int numbers[], int size)The function call transfers control to the function. It consists of the function name followed by the list of parameters in parentheses. Note that the parentheses must be used even if there are no parameters.
{
for (int i=0; i < size; i++)
cout << numbers[i] << endl;
}
#include <iostream>
// Example prototypes at top of file:
// void functions do not return a value.
void Welcome(int);
// empty parameter list
void Greetings();
// function that must return a value, parameter names are optional
double doCalc(double a, double b);
// Example calls in main:
int main()
{
Welcome(5);
Greetings();
double a = 4.3; // just to show passing an argument
double value = doCalc(a, 16.5);
}
// Example function definitions
// Notice that the function header (first line) is the same, except prototypes have a
// semicolon at the end.
// start with function header, then function body
void Welcome(int numStars)
{
for (int i=0; i<numStars; i++)
cout << "*";
cout << endl << "Welcome\n"; // "\n" forces line feed
}
void Greetings()
{
cout << "Greetings, earthling\n";
}
double doCalc(double a, double b)
{
return a*a + b*a; // must have return of type double
}
Used for |
Library to include |
Screen IO |
<iostream> |
File IO |
<fstream> |
Various, such as exit, rand, etc. |
<cstdlib> |
Math |
<math> |
IO formatting |
<iomanip> |
char reply;Operators
do
{
cout << "Enter y or n: ";
cin >> reply;
} while (reply != 'y' && reply != 'n');
sum = 0;
count = 1;
while (count < 10)
{
sum += count;
count++;
}
sum = 0;
for (int count=1; count<10; count++)
sum += count;
Mathematical: + - / * % += -= /= *= %=Also bitwise operators, which have not been covered in MACS 261.
Relational: < > <= >= !=
Logical: || && !
void doSomething(int x) // makes a local copy, initialized with parameter valueParameters can also be passed by reference, which means that the address of the variable is passed in, so both the function and main are referencing the same memory location. Note the & after int, which indicates this is a reference parameter (similar to a pointer, but it doesn't need to be dereferenced).
{
x = 2 * x; // modifies local copy, in this example x is assigned 20
}
int main()
{
int y = 10;
doSomething(y);
cout << y << endl; // y will still have the value of 10
}
// parameter MUST be a variable... can't change the value of a literal
void doItAgain(int& x) // x looks at memory location of parameter
{
x = 2 * x;
}
int main()
{
int y = 10;
doSomething(y);
cout << y << endl; // y will now have the value of 20
}
// pointer declaration uses *, must include the data typeC++ example 2 (commonly use pointers with arrays)
int* iptr;
// new is used to allocate space, just one int in this example
iptr = new int;
// pointer must be dereferenced using * to access contents
*iptr = 3;
cout << "iptr value: " << *iptr << endl;
// without dereferencing, you would be printing the memory address
cout << "address: " << iptr << endl;
// pointer declaration same above, initialize to NULL for safety
int* arrayPtr = NULL;
// by specifying size in brackets, arrayPtr is now an array
arrayPtr = new int[10];
// normal array syntax can be used to access
for (int i=0; i<10; i++)
arrayPtr[i] = 0;
// assume arrayPtr is used in some way here
// now return the memory to the heap
delete[] arrayPtr;
Corresponding Java program:
// Libraries are listed at the top
#include <iostream> // library for IO
using namespace std;
// every C/C++ program must have a main method, which will should be int.
//main is the function invoked when you execute the program.
int main()
{ // as in Java, function bodies are surrounded by braces
cout << "Hello World\n"; // see Simple input/output
}
// program is included within HelloWorld class, main is a static function (canSelection (decisions)
// be called with no object).
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
char reply;
cout << "Enter y or n: ";
cin >> reply;
if (reply != 'y' && reply != 'n')
cout << "Invalid response!\n";
// score is an int containing test grade
if (score >= 90)
cout << "Grade: A\n";
else if (score >= 80)
cout << "Grade: B\n";
else if (score >= 70)
cout << "Grade: C\n";
// can use compound conditions
if (score >= 80 && score < 90)
cout << "Grade: B\n";
// the following assumes a menu was displayed
int menu;
cin >> menu;
switch (menu) {
case 1: // equivalent to if (menu == 1)
doOne();
break; // remember that without this, control continues to next case
case 2:
doTwo();
break;
default:
cout << "Invalid menu option!\n";
}
int number;Corresponding Java code:
cout << "Enter a number: "; // displays a prompt on the screen
cin >> number; // reads 1 integer, stops at white space
cout << "You entered " << number << endl; // endl moves to next line
int number;Struct
System.out.print("Enter a number: ");
number = Integer.parseInt(stdin); // assumes stdin appropriately declared
System.out.println("You entered " + number); // println forces move to next line
// define the Date data type. The identifier is called the structure tag.
struct Date
{
// list the members
int month, day, year;
}; // end with a semicolon.int main()
{
// Use the Data datatype, which allocates 3 ints for each variable.
Date birthday, expiration;// members can be accessed using the dot operator
birthday.month = 1;
birthday.day = 10;
birthday.year = 1980;// structs can be treated as a whole
cout << "Birthday\n";
expiration = birthday;
expiration.year = 2002;
// members must be printed individually, << is not defined for the struct
cout << birthday.month << "/" << birthday.day << "/" << birthday.year;
cout << "Expiration\n";
cout << expiration.month << "/" << expiration.day << "/" << expiration.year;
}
Variable declarations
C++ |
Java |
Comments |
int anInt; | int anInt; | whole numbers, also have short, long etc. |
double aDouble; | double aDouble; | decimal numbers, also have float. |
char aChar; | char aChar; | Single quotes 'Y' |
bool found; |
boolean found; |
true/false. C++ recognizes 0 as false, any
other value as true. |
C++
|
Java
|
Comments |
const int MAX = 5; |
final int MAX = 5; |
C++ |
Java |
Comments |
Point aPoint; | Point aPoint; |
In C++, the declaration allocates space. In Java, new must be used. |
C++
|
Java
|
Comments |
int nums[10]; |
int nums; nums = new int[10]; |
In C++, declaration allocates space. In Java, new must be used. |
C++
|
Java
|
Comments |
int* p; p = new int[5]; |
n/a |
C++ has a pointer type. Allocates space
for the pointer, but not for the data. In Java, ALL object
declarations are references. |