The first meeting was preoccupied with two things. First, it was necessary to become familiar with the programming environment; in particular, the MS Visual Studio. Writing a simple C++ program requires creating a project and adding files to it. I have described this process on the Visual Studio page. It takes some getting used to, but as usual your comfort level will improve with experience. By the way, I don't want to discourage anyone from using another compiler (Borland, Symantec, etc.) if that is what you have access to. However, we are constrained to use the Visual C++ development package during our lab time.
During the class, we wrote a simple hello program as follows:
//file: hello.cpp
#include <iostream.h>
void main(void)
{
cout << "Hello World" << endl;
}
Note that in C++, the I/O procedures are supplied in libraries, like <iostream.h>, which are themselves written in C++. The advantage to this approach is that these objects can be extended or changed by anyone who thinks they have a better way.
Note that the main program here is a function with input and output types (both void or empty in the example). The name of this function must be "main". Our program can make use of other functions, but there must be one and only one function named main (our program).
As a simple introduction to functions (which are central to C and C++), we constructed the following example:
//file: sum.cpp
#include <iostream.h>
int sum(int a, int b)
{
return a + b; // Note the difference
from usual Pascal sum := a + b;
}
int main(void)
{
int x = 3, y = 8; //
Note that you can initialize variables at definition.
cout << x << " + " << y
<< " = " << sum(x, y) << endl;
// << called "insertion" operator;
strings are set off by ", not ';
// endl does two things: (1)
inserts new line and (2) "flushes" output buffer.
return 0;
}
We'll talk more about functions soon.
Next we introduced some of the C++ control structures. In particular, the if-else and switch selection structures. The following problem was posed:
input: A character
output: A statement indicating whether or not the input character is a vowel (A,E,I,O,U).
Solution 1
//file: vowels.cpp
#include <iostream.h>
int main()
{
char c;
// INPUT SECTION
cout << "Please type a character ";
cin >> c;
// CALCULATION AND OUTPUT
if (c == 'A' || c == 'a') //NOTE:
The relational operator testing for equality is ==, NOT =
cout << c << " is a
vowel." << endl;
else if (c == 'E' || c == 'e')
cout << c << " is a
vowel." << endl;
else if (c == 'I' || c == 'i')
cout << c << " is a
vowel." << endl;
else if (c == 'O' || c == 'o')
cout << c << " is a
vowel." << endl;
else if (c == 'U' || c == 'u')
cout << c << " is a
vowel." << endl;
else
cout << c << " is not a
vowel." << endl;
return 0;
}
With the introduction of the switch statement, the code is somewhat simplified:
Solution 2
//file: switch.cpp
// CALCULATION AND OUTPUT
switch (c)
{
case 'A': case
'a':
case 'E': case
'e':
case 'I': case
'i':
case 'O': case
'o':
case 'U': case
'u':
cout << c << " is a vowel." << endl;
break;
default:
cout << c
<< " is not a vowel." << endl;
} // end of switch statement
Note that, after a case is selected, exit from the statement is not automatic. It requires a break statement to exit. Also, note that the switch expression (c in this example) must be integral (e.g., int, char, bool, etc.), floating point objects are not allowed. Finally, the case values must be constants.
We then discussed a few C/C++ idiosyncrasies. C programmers have traditionally gone for the succinct, sometimes cryptic, solution to programming problems. Solutions that are very brief and clever, but generally inpenetrable by the average person. This tradition has been under attack in recent years. As the size and complexity of programs has grown, it has become more important that programs be understandable and maintainable than that they be efficient. In any case, the following are some features of C inherited by C++ that can be useful, but in moderation.
The assignment statement itself has a value.
x = y = z = 3;
The assignments associate from the right and each has the value assigned to the variable.
sum += x; ======> sum = sum + x; this applies also to the other arithmetic operators -, *, and /.
i++; ======> i = i + 1;
i--; ======> i = i - 1;
j = i++ + 2; ======> j = i + 2;
i = i + 1;
j = ++i + 2; ======> i = i + 1;
j = i + 2;
Finally, the precedence of operators is, of course, important so I have gathered together them together in one place for reference when necessary.
Example. Write a program that converts all lowercase letters to uppercase. We'll assume keyboard input.
//You can download characters.cpp to play with
#include <iostream.h>
int main()
{
char c;while (cin >> c){ // ignores white space
if (c >= 'a' && c <= 'z)
// NOT necessary to write (c >= 97 && c <= 122)
c += 'A' - 'a';
cout << c;
}return 0;
}
So if the input to this program is: "This is a test.", the output will be "THISISATEST."
Note that the spaces between words have been eliminated. If you wish to preserve the white space characters, then one of the following alternatives is required:
while ((c =cin.get()) != EOF){...} //Download characters2.cpp
or while (cin.get(c)){...}
The "member" function (we'll discuss this later) get() returns the value of the character extracted from the stream, while the member function get(c) returns true (1) until the character extracted is the EOF (end of file) character, at which time it returns false (0).
Finally, you should be acquainted with the "old" C library of character processing functions declared in the header file ctype.h. The current example could then be written as follows:
Download characters3.cpp
#include <ctype.h> //This header file has nifty functions
like toupper(), tolower(), etc....
#include <iostream.h>
int main()
{
char c;
while (cin.get(c))
{
c = toupper(c); //<----
Pretty neat, huh?
cout << c;
}
return 0;
}
Check the other functions in ctype.h by browsing the include directory (Tools->Options->Directories), select, copy and paste the directory into Find File, and viewing ctype.h. You'll find the following function definitions:
isalnum (c) // true if c is alphabetic or digit character
isalpha (c) // true if c is an alphabetic character
isdigit (c) // true if c is a decimal digit
islower (c) // true if c is a lower case letter
isupper (c) // true if c is an upper case letter
isspace (c) // true if c is a space, form feed, newline, carriage return, or tab character
tolower (c) // returns the lower case equivalent (if any) of c, otherwise returns c
toupper (c) // returns the upper case equivalent (if any) of c, otherwise returns c
It should be noted that for all of these functions, both the return value and the parameter, c, are of type int. This may seem strange until you remember that, in C, there is no boolean type (0 ~ false, not 0 ~ true) and characters are interchangeable with short integers.
Finally, we introduced the syntax necessary to incorporate text files into your programs. This will make creating homework hardcopy MUCH easier!
To repeat the above example with an input text file, "text.txt", and an output file, "upper.txt", we have:
//Download text.txt as the input file for the following program
//file: characters4.cpp
#include <fstream.h>
#include <ctype.h>
int main()
{
ifstream fin ("text.txt"); // input file
ofstream fout ("upper.txt"); // output file
char c;
while (fin.get(c)){
c = toupper(c);
fout << c;
}
fout << endl;
return 0;
}
Lab Exercise. Write a program that reads a list of numbers and outputs the list together with a statement giving the average of the list. Use text files for both input and output. I recommend that you try this on your own. I have constructed a program that accomplishes the task and you can download the solution if you wish.