Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
C++ Basics
Here is the general format for a C++ program:
File:
program.cpp
/* Comments */
// More comments
#include <iostream>
#include <string>
…
// Provides access to standard code libraries
#include "myclass.h"
// Provides access to user-defined code
int g;
// Global variables defined here
using namespace std;
// Defines the namespace we’re using
// Define any functions here that are available globally, e.g.
void someFunc() {
// code
}
int main(char *argv[], int argc)
// Parameters optional
{
// Code here for main returning an int value
}
Later on we will give the format to define classes. For now let’s see some basic innards
that make up a typical C++ program.
Primitive Data Types: Declaring variables with primitive data types is dust like Java and
C. There are some differences with scoping that we will discuss later when we discuss
classes and objects
Typical data types: char, int, long, float, double, bool (not boolean)
C++ treats 0 as false and non-zero as true
They behave the same as you would expect, just like in C or Java. This means
there are the same pitfalls. For example, if we divide integers:
double x = (2 / 3) * 6;
gives us 0 because we do integer division for 2/3 which results in 0 * 6.
The new C++ 11 standard has a new data type called “auto”. If we use this as the data
type then C++ will try to deduce what the type is based on the expression on the right
hand side of the assignment.
For example we could write:
double x = 3.15 * 3;
auto y = x * 10;
This makes y into a double because the compiler see’s that x is a double and sets y
accordingly. For the primitive data types this is not particularly useful, but when we get
to really long data types using templates then the auto notation because much cleaner.
To compile a program using C++11 we have to add the –std=c++11 flag when using g++.
This is for version 4.7 or higher. Older versions of g++ require –std=c++0x. Even older
versions don’t support C++11 at all.
Here is an example from the command line of tikishla:
g++ test.cpp –std=c++11
C++11 also has a way to retrieve the data type of a declared variable. It is decltype:
decltype(x) y = x * 10;
This retrieves the type of x (a double) and creates y as a double.
Later we will see interesting uses for auto and decltype with functions, and especially
when we get to talk about templates and classes. Until then, you are probably better off
using the old format of specifying a primitive data type.
Strings:
In both C++ and Java we can hard-code a string using double-quotes. However, C++ and
Java natively treat strings differently. Java has a built-in string class. Core C++ strings
are defined as arrays of char. The null character \0 is used to terminate a string. C++
does include a Standard Template Library (STL) implementation of a “string” data type
that behaves similarly to a Java string. (The STL library includes common data
structures, such as a vector, hash table, etc.)
To use the STL strings, we must #include <string> at the top of each file that wishes to
use strings. Here is an example:
#include <string>
using namespace std;
int main()
{
string s;
// Note lowercase string, not String
s = "hello";
s = "hello" + "there";
// Concatenation
s.length();
// Returns # of chars in the string
s[0];
s[1];
return 0;
// References character ‘h’
// References character ‘e’
}
Output: To print data to the console, use:
cout << data_to_print;
For example:
cout << "hello world";
cout << s << " " << x+3;
// Outputs hello world
// Outputs string s concatenated with x+3
To print a newline at the end of the output use endl:
cout << "hello world" << endl;
We can also include the various escape characters (\n, \r, \”, etc.) in the string.
Input: To read data from the keyboard, use cin. For example:
int x;
double d;
cin >> x;
cout << x << endl;
cin >> x >> d;
// Reads an integer from the keyboard into x
// Output what the user entered
// Input into multiple variables
If we are inputting into a string, this doesn’t quite behave as expected if there are spaces
in the input. cin only inputs data to the first whitespace, so if we have input with spaces
we don’t get the desired result:
string s;
cin >> s;
cout << s << endl;
cin >> s;
cout << s << endl;
// User types “hello world”
// Outputs “hello”
// Reads in the “world” part
// Outputs “world”
To avoid this problem we can use various functions such as getline() to input a string to
the newline. We’ll discuss this later.
Boolean expressions, arithmetic operators, relational operators: Just like Java and C
If statement: Just like Java and C.
One exception from Java is that any non-zero value is considered to be true, while zero is
considered to be false. So we could make a statement such as:
if (1) { … } which amounts to : if (true) { … }
Assignment statement: Just like Java and C
One common pitfall is confusing = with ==. While Java will flag this as an error, C++
will not because it is considered legal. An example is below:
int i=0;
if (i=1) { … }
The body of the if statement will always be executed because in the expression “i=1” we
assign the value 1 into i, and the value tested by the if statement amounts to if (1) {…}
As we have seen this is considered true, so we will execute the boy of the statement and
at the same time variable i is set to 1.
For loop, while loop, do-while loop, break, continue: Just like Java and C
Defining functions: Mostly like defining a method in Java and a function in C
We’ll cover differences in passing by value or reference later, but the general way we
define and use a function is pretty close to what you are used to.
Essentially we have:
<return type> functionName(parmType parmName, parmType, parmName…)
{
… code …
return (something of type <return type>;
}
It is typical to define the function prototype, or function header, somewhere near the top
of the program. This tells the compiler that the function exists so we can reference it
before the implementation may be defined. The function prototype is basically the first
line of the function, defining the return type and parameters. You don’t need to put
variable names in for the parameters, but most people put them there for a little extra
information.
For example:
int addOne(int y);
int addOne(int y)
{
y++;
return y;
}
// function prototype
int main()
{
int x = 3;
cout << addOne(x) << " " << x << endl;
return 0;
}
// Outputs 4 3
C++ lets us use the keyword const to make things constant and unchangeable, but it can
be used in many different ways that can be confusing.
const int x = 3;
int const x = 3;
and
both make x a constant that is an integer set to 3. You can’t change x. In general, the
thing to the left is what the const applies to, unless there is nothing there, in which case
the const applies to the thing to the right.
We will see how const is used with functions/methods later and that is where it starts to
get confusing.
Basically we have covered a good chunk of the “C” part of C++. Here is a sample
program that illustrates most of the points covered so far. Given a distance in miles and a
time in minutes and seconds, it calculates the speed/pace to cover that distance in
minutes/mile. Once again everything should look pretty familiar!
#include <iostream>
#include <string>
using namespace std;
int getMinutesPace(double distance, int minutes, int seconds);
int getSecondsPace(double distance, int minutes, int seconds);
int getMinutesPace(double distance, int minutes, int seconds)
{
double totalMinutes = minutes + (seconds / 60.0);
double minutesPerMile = totalMinutes / distance;
return (int) minutesPerMile; // Truncate anything after
decimal point
}
int getSecondsPace(double distance, int minutes, int seconds)
{
double
double
// Get
return
totalMinutes = minutes + (seconds / 60.0);
minutesPerMile = totalMinutes / distance;
what is after the decimal point and multiply by 60
(minutesPerMile - (int) minutesPerMile) * 60;
}
int main()
{
string firstName;
char c;
double distance;
int minutes, seconds;
do
{
cout << "What is your first name? " << endl;
cin >> firstName;
cout << "How many miles did you travel? ";
cin >> distance;
cout << "How many minutes and seconds did it take? ";
cin >> minutes >> seconds;
cout << firstName << ", your pace is " <<
getMinutesPace(distance, minutes, seconds) <<
" minutes and "
<< getSecondsPace(distance, minutes, seconds)
<< " seconds per mile." << endl;
cout << "Do again? " << endl;
cin >> c;
} while (c=='y');
return 0;
}
Java Basics
Here is the general format for a Java program. At this point we are doing the minimal
with regard to defining our own classes/objects, but more on that will come soon.
File:
ProgramName.java
/* Comments */
// More comments
import java.util.Scanner; // Sample import for I/O
…
// Provides access to standard code libraries
// Can’t define global variables here
public class ProgramName
{
// For now everything is static to make it behave like C.
// Later we will make these non-static
// Use public or private
// These are variables accessible inside this class
public static int varName;
private static double varName2;
public static
{
.. code
}
…
public static
{
.. code
}
<return-type> methodName(parameters)
..
void main(String[] args)
for main ..
}
Here are the standard data types:
Arithmetic expressions, iteration, control structures, etc. behave just like C++. To input
data from the keyboard we use the Scanner class. Here is an example:
import java.util.Scanner;
public class ScannerTest
{
public static void main(String[] argv)
{
int i;
float f;
double d;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter an integer. ");
i = keyboard.nextInt();
System.out.println("You entered: " + i);
System.out.println("Enter a double. ");
d = keyboard.nextDouble();
System.out.println("You entered: " + d);
System.out.println("Enter a float. ");
f = keyboard.nextFloat();
System.out.println("You entered: " + f);
// Now sum up all three things entered as a double
d = d + (double) f + (double) i;
System.out.println("The sum of all three is: " + d);
}
}
We start with the “import java.util.Scanner” which gives us access to the
code library containing the Scanner class, which allows us to input data from the
keyboard. This line should be near the top of the file.
Inside the main method the line “Scanner keyboard = new Scanner(System.in);” creates a
Scanner object that takes System.in as a parameter, which refers to input from the
keyboard. This is basically defining a variable with a data type of “Scanner” and the
name of the variable is “keyboard”. We could have used a different name.
With the keyboard variable we can now use the nextInt(), nextDouble(), or nextFloat()
methods to return numbers of those particular data types typed from the keyboard. A
method is a name for a group of code that performs some specific task – in this case, it
reads in whatever is typed “next” as a double, integer, float, etc. This method is defined
for you as part of the Java language.
Here is the output for a sample run:
Enter an integer.
5
You entered: 5
Enter a double.
2.412
You entered: 2.412
Enter a float.
3.14
You entered: 3.14
// Note roundoff errors below!
The sum of all three is: 10.552000104904174
Formatted Output
So far we have been using System.out.println to output all of our messages. This method
outputs whatever is inside the parentheses and then adds a newline (future output goes to
the next line).
If you don’t want output to go to the next line then use System.out.print instead of
System.out.println. For example:
System.out.print("The Seawolf mascot's name is ");
System.out.println("Spirit");
Outputs:
The Seawolf mascot's name is Spirit
You can use combinations print() and println() to control how you output different
variables. You have probably noticed that when you output floating point numbers you
are often getting more decimal places than you really want. In an earlier example, the
output was 10.552000104904174 but you might want to only output it as 10.55. An
easy way to do this is to use the printf() method which allows you to format your output.
Here is an example that shows a few format specifiers, one to print an integer, an integer
in a field of 5 spaces, and a floating point number with 2 digits after the decimal point:
int num1, num2;
double num3;
num1 = 1;
num2 = 9;
num3 = 5.58831;
System.out.printf("An integer:%d\nAn integer in 5 spaces:%5d\nA
floating point number with 2 decimal places:%.2f\n",num1,num2,num3);
Output:
An integer:1
An integer in 5 spaces:
9
A floating point number with 2 decimal places:5.59
The % symbol is used in the printf statement as placeholders to substitute values that are
specified after the string.
In this case “%d” is a placeholder for the first argument to come after the string which is
the variable num1. “%d” stands for an integer, so it will output as an integer the value in
num1.
“%5d” is the next placeholder and it means to output an integer, but do so in a field of 5
characters. You can use this if you want to make columns of numbers line up nicely, for
example, to make a table. In this case it matches up with the second argument, which is
the value stored in num2.
“%.2f” is the next placeholder and it means to output a floating point number with 2
places after the decimal point. It matches up with the third argument, which is the value
stored in num3. Note that the number is rounded up when it is printed out.
There are more format specifiers the next most common one is %s which is a placeholder
for a String – see a Java reference for details.
Inputting Strings
Reading input from the keyboard for strings is almost the same as inputting numbers,
except there is a pitfall when reading an entire line vs. reading a single number or word.
To read in a single word (surrounded by whitespace, i.e. spaces, tabs, carriage returns,
etc.) use the next() method:
public static void main(String[] argv)
{
int i;
String s;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter an integer. ");
i = keyboard.nextInt();
System.out.println("You entered: " + i);
System.out.println("Enter a word. ");
s = keyboard.next();
System.out.println("Your word was: " + s);
}
This program reads in an integer, prints it out, then reads in a word and prints it out.
For example:
Enter an integer.
5
You entered: 5
Enter a word.
coffee
Your word was: coffee
If you enter more than one word note that the next() method ONLY reads the next word:
Enter an integer.
5
You entered: 5
Enter a word.
need more coffee
Your word was: need
To read a whole line we can use the method nextLine():
public static void main(String[] argv)
{
int i;
String s;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter an integer. ");
i = keyboard.nextInt();
System.out.println("You entered: " + i);
System.out.println("Enter a line of text. ");
s = keyboard.nextLine();
System.out.println("Your line was: " + s);
}
You would probably expect it to behave like the first program, but the program
immediately ends without prompting you to enter a line of text. The reason is because
the nextLine() method behaves a little differently than the other methods.
Java interprets its input as a stream of characters. When you press the enter key, a
newline character is inserted into the stream. Let’s say that you are giving the input of
“50” for the integer and “hello” for the text. Java sees this input as:
50\nhello\n
next character to read
The \n is a single character for newline.
When we execute: i = keyboard.nextInt();
Java reads the 50 and advances its input buffer to reference the next character in the
stream, the \n:
50\nhello\n
next character to read
If we execute: s = keyboard.next();
(or nextInt() or nextDouble, etc.)
then Java will skip any whitespace characters looking for a word that is surrounded by
whitespace. You can test this by entering leading spaces, newlines, tabs, etc. They will
all be skipped and Java will return back only the word you enter.
However, if we execute: s = keyboard.nextLine();
then Java will stop until it hits a newline character, and consume it. It just so happens
that the next whitespace is the \n so we end up with:
50\nhello\n
next character to read
And the string s contains a blank string.
The solution? Use an extra nextLine() after reading an int or word to skip the whitespace
character if you want to later read in an entire line:
public static void main(String[] argv)
{
int i;
String s;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter an integer. ");
i = keyboard.nextInt();
System.out.println("You entered: " + i);
keyboard.nextLine();
// Skip \n character
System.out.println("Enter a line of text. ");
s = keyboard.nextLine();
System.out.println("Your line was: " + s);
}
Working with Strings
The String type is actually a class, as opposed to a primitive data type like int’s or char’s.
As a class, this means that the String type stores both data and methods. The methods
perform various operations on the string data that it holds.
Concatenation: The “+” operator, when applied to numbers, performs addition.
However, when applied to strings, this concatenates two strings together. For example:
String s1 = "hello";
String s2;
s2 = s1 + "there";
System.out.println(s2);
This code fragment will output “hellothere”. Notice there is no space that is added. If we
want to explicitly add a space, we must put one there:
s2 = s1 + " there";
Concatenation will convert any other data types in the expression into strings. For
example:
s2 = s1 + " " + 100;
System.out.println(s2);
This will output “hello 100”. What Java really does is take the number 100 and turn it
into a string before concatenating it with s1.
Here we jump straight to the same program example to compute pace, but in Java instead:
import java.util.Scanner;
public class Test
{
public static int getMinutesPace(double distance, int minutes, int
seconds)
{
double totalMinutes = minutes + (seconds / 60.0);
double minutesPerMile = totalMinutes / distance;
return (int) minutesPerMile; // Truncate anything after decimal
point
}
public static int getSecondsPace(double distance, int minutes, int
seconds)
{
double totalMinutes = minutes + (seconds / 60.0);
double minutesPerMile = totalMinutes / distance;
// Get what is after the decimal point and multiply by 60
// Java is a little pickier on the type conversion
return (int) ((minutesPerMile - (int) minutesPerMile) * 60);
}
public static void main(String[] args)
{
String firstName, s;
double distance;
int minutes, seconds;
Scanner keyboard = new Scanner(System.in);
do
{
System.out.println("What is your first name? ");
firstName = keyboard.next();
System.out.println("How many miles did you travel? ");
distance = keyboard.nextDouble();
System.out.println("How many minutes and seconds did it take?");
minutes = keyboard.nextInt();
seconds = keyboard.nextInt();
System.out.printf("%s, your pace is %d minutes and %d seconds per
mile.", firstName, getMinutesPace(distance, minutes, seconds),
getSecondsPace(distance, minutes, seconds));
System.out.println("\n\nDo again? ");
// No scanner for an individual char, so using a string
s = keyboard.next();
} while (s.charAt(0)=='y');
}
}