Professional Documents
Culture Documents
First Program
\n newline
\r carriage return (not common)
\t tab
\a alert (beep)
\\ backslash
\’ single quote
\” double quote
Your First C++ Program
#include <iostream.h>
void main ( ) {
cout << “Hello World” << endl;
}
#include <iostream.h>
Begin the main
void main ( ) {
cout << “Hello World” << endl;
}
End the main End a single statement
Compiling Your Program
• You’ll use one of two things:
• The command-line: g++ (on Unix)
• Your IDE (like Visual C++)
• When you compile, you’ll have one of two things happen:
• It compiles
• It doesn’t
• If it doesn’t compile, you have syntax errors
Knowing When to Compile
• As a rule, the less comfortable you are, the more you should compile
• This isolates the errors
• As a rule, compile:
• After you type in the skeleton
• After every 5 or 10 lines of new code
• Don’t become dependent on the compiler!
Variables
• Computer programs manipulate data
• There is a need to store data
• Variables:
• Represent a named cell in the computer’s memory
• Used to hold information
• When you declare a variable:
• You open up some of the computer’s memory
• You’re giving the variable an identifier (name)
• You only do this once per variable
Data Types
• A data type describes the kind of information a variable
can hold
• Some data types are built into the language
• Some data types we define ourselves (later)
• Different Forms:
• Primitive data types
• Complex data types
Primitive Data Types
• These are the simplest kinds of data types
• Built-in
• Whole numbers:
• short (relatively small numbers)
• int (larger numbers)
• long (VERY large numbers)
• Number of bytes these take up depends on compiler and OS!
Primitive Data Types
• Decimal numbers:
• float (less precise than a double)
• double (more precise than a float)
• Precision means how many numbers come after the decimal point
• Others:
• char (holds characters like ‘a’, ‘A’, ‘1’, ‘ ‘)
• bool (holds only a true or false value)
How to Declare a Variable
(of any type)
• Format:
<data type> <variable name>;
• Variable name you can choose almost anything
• Examples:
age gpa
byte age;
float gpa;
String name;
char letterGrade; name letterGrade
How Big is it: sizeof( )
long long
long
short
short short
Operators
• + adds two variables/literals together (including
Strings)
• - subtraction
• / division
• * multiplication
• % modulus (remainder)
• ( and ) follows standard math rules
• Example:
int result = ( (4 % 3) * 5) + 1; // result gets 6
Type Casting
• This occurs when you want to put something larger into something smaller
• Can possibly lose precision or value
• Has format:
<smaller var> = (<smaller data type>)<larger var>;
• Example:
long myLong = 17;
short myShort = (short)myLong;
// We are squeezing myLong into myShort!
Exercises