Getting Started in C++

Tom Kelliher, CS17

Feb. 21, 1996

Your First Program

/**********************************************************************
 * convert.cc
 * Tom Kelliher
 * CS18, Feb. 21, 1996
 * 
 * This program will prompt for a temperature in degrees Fahrenheit,
 * convert it to degrees Celsius, and output the converted temperature.
 * Input from the keyboard
 * Output to the console
 **********************************************************************/

// Preprocessor directives:
#include <iostream.h>

// Named constant definitions:
const float FRACTION = 5.0 / 9.0;

// Main program:

int main()
{
   float fahrenheit;   // fahrenheit temperature
   float celsius;      // celsius temperature
   
   // program statements follow
   cout << "Please enter a temperature in degrees Fahrenheit: ";
   cin >> fahrenheit;
   
   celsius = FRACTION * (fahrenheit - 32.0);
   
   cout << "That is " << celsius << " degrees Celsius" << endl;
}

Program Elements

Comments

Preprocessor Directives

Data Types and Type Declarations

Data type:

a set of data values and a set of operations on those values.

Examples:

int counter;
char more;
float size;
double distance;
Types, variables

Characteristics:

Fundamental vs. derived types

Some fundamental types:

Initialization in declaration:

int size = 10;
char more = 'y';
double fahrenheit = 1.23E9;

Named Constants

A ``variable'' with unchanging value:

const double PI = 3.14159;
const int FEET_PER_MILE = 5280;

Traditional:

Statements, Compound Statements

The main function

Some Basic C++ Statements

Arithmetic Expressions

Assignment operator: =

Assignment expression statement form:

variable = arithmeticExpression;

Arithmetic operators:

Precedence, associativity

value = 1 + 2 * 3 + 4;
value = 10 - 8 - 4;

I/O Statements

cout << "Enter two integers: ";
cin >> value1;
cin >> value2;
cout << "Their sum is: " << value1 + value2 << "." << endl;

Programming Style

The Goal: your program should be easy to read and understand

Points:



Thomas P. Kelliher
Wed Feb 21 11:17:55 EST 1996
Tom Kelliher