// This program demonstrates some basic programming
// techniques in C++. Besides being lecture notes,
// it is also a fully functioning program which you
// may load into Visual C++, compile, and run.
// How to specify your #include's
#include <iostream.h>
#include <stdio.h>
// How to specify your main function
void main()
{
// How to declare an integer
int x;
// How to declare multiple integers
int y,z;
// How to declare a floating point number
double w;
// How to set the value of a variable
x = 25;
w = 25.2542342;
// More complex arithmetic expressions
y = 3*x*x - 2*x + 17;
z = (y - 42) / (x + 17);
// How to print out a message (endl == end of line)
cout << "This will print out a message." << endl;
// How to print out a variable value
cout << x << endl;
// How to print out a message and a variable value
cout << "The value of x is " << x << endl;
// How to read in a variable value
cin >> y;
// How to read in a variable value with a prompt
// (note: do not use "endl"):
cout << "Please enter a number (0 to exit): ";
cin >> y;
// How to write a simple conditional ("if") statement
if (x < y)
{
// This code is only called if x < y
cout << x << " is less than " << y <<
endl;
}
// How to write a conditional with an else statement
if (x < y)
{
// This code is only called if x < y
cout << x << " is less than " << y <<
endl;
}
else
{
// This code is only called if x >= y
cout << x << " is not less than " << y
<< endl;
}
// How to test for equality in a conditional
if (x == y)
{
// This code is only called if x equals y
cout << x << " equals " << y <<
endl;
}
// How to test for inequality in a conditional
if (x != y)
{
// This code is only called if x does not equal y
cout << x << " does not equal " << y <<
endl;
}
// How to test for both of two conditions (logical AND)
if ((x < y) && (y > 2))
{
// This code is only called if x > y
// *AND* y > 2
cout << "x>y and y>2" << endl;
}
// How to test for either of two conditions (logical OR)
if ((x < y) || (y > 2))
{
// This code is only called if x > y
// *OR* y > 2
cout << "x>y or y>2" << endl;
}
// How to test for the negation of a condition (logical NOT)
if (!(x < y))
{
// This code is only called if it is *not* true
// that x < y (that is, if x >= y)
cout << "x is not less than y" << endl;
}
// How to loop using WHILE
x = 10;
y = 0;
while (y < x)
{
// This code is called repeatedly until it is
// NOT true that y < x
cout << "y = " << y << endl;
y = y + 1;
}
// How to not exit the program until the user
// hits the Enter key
cout << "Please hit Enter to exit the program." <<
endl;
getchar();
// How to exit the main() function immediately: return
if (x <= 0)
{
// This code is only called if x <= 0
// It uses "return" to immediately exit the main() function
return;
}
}