CSC261 Programming Languages I, C/C++ Instructor: Glenn Lancaster Office: 832 CTI, 243 South Wabash Phone: 312-362-8718 (with voice mail) Email: glancast@cs.depaul.edu Office Hours for this course: 1:30 - 2:45 TTh and by appointment
I check email much more often than the phone's voice mail.
No appointment is necessary during office hours.
To make an appointment, it is best to email me or let me know during class when you would like to see me.
Homework should be submitted through the Course Online site for this course. If multiple files are to be submitted, please use zip or winzip or similar compression utility to first combine all the files into one zip file. Then submit that file.
Homework grades and comments will be posted individually on the Course Online site.
Homwork will consist mostly of program assignments. These are to be submitted on the Course Online site for this course. There will be 7 assignments.
Late programs turned in after the due date, but within one week will be penalized 1 point for each day late. If a program is later than one week, the penalty is 12 points plus 1 point for each additional day late.
Grades will be determined as follows:
Homework: 60% Midterm: 20% Final: 20%
CTI, Room 832 Phone: 312-362-8718 TTh: 1:30 - 2:45pm and by appointment
Most notes and sample code will be available on this website:
http://condor.depaul.edu/~glancast/261class/.rdmeframe.html
Language B, written in by Ken Thompson in 1970, was developed as the language in which to write the code for the Unix operating system on a DEC PDP-7 (minicomputer of the time).
B was a typeless language. All data was just bits and any operators could be used on any data.
C evolved from B, but provides a variety of data types: characters, integers and floating point numbers of a variety of sizes plus a hierarchy of types created with pointers, arrays, and structures. In C each data type has an associated set of operators that can be performed on the type. Other operations are not allowed. The orignal language manual for C was published around 1978.
Both B and C were devloped at Bell Labs.
C++ was developed initially and primarily by Bjarne Stroustroup and also developed at Bell Labs. A course on C++ was held by Stroustroup at Bell Labs in Ohio in 1985. Many of the Bell Labs attendees of this course as well as others have contributed to the development of C++ from 1985 to 1991.
C++ is (essentially) a (big) extension of C; that is, generally any valid C program is already a valid C++ program.
C is a procedural language.
C++ adds features that make it also an object oriented language.
To write and run a C++ program, you must have a translator or compiler that translates C++ code into the machine language of the computer you will use.
There are many different compilers available (not just Microsoft). Some are free.
In addition, some compilers are part of IDE - Integrated Development Environment, while other compilers stand alone and must be used with other tools.
In general, one would like to have at least three tools, and the first two are essential:
Editor To write the code and save it as a file. E.g., the same function that stand alone editors such as Notepad, Textpad, Wordpad, Word, Emacs, Vi, etc. provide. Compiler/Linker After the code has been written with the editor, it must be translated to machine code (by the compiler) and linked (by the linker!) with standard library code for common operations such as input/output to produce an executable program file. Debugger This is a tool that is often provided with IDE's that allow you to step through the execution of a program one statement at a time and to examine and/or change the values that are being computed.
Some compilers and IDE's and Editors:
Visual C++ 6 (IDE from Microsoft) Visual C++.NET (IDE from Microsoft; requires the .NET framework) Bloodshed's DEV-C++ (free or donation)(IDE) GNU g++ compiler and tools (You will need some editor) Cygwin (A port of GNU g++ compiler and Unix utilities for Windows; not an IDE. You still need an editor. Has a debugger, but it is a stand alone, not integrated. Emacs: An editor; but can be configured for use with g++ and its debugger to provide an integrated environment of sorts. Textpad: An editor; better than notepad. It can also be configured to use the g++ compiler. Doesn't provide support for the debugger.
bool true or false char single character (or very small integer) short small integer int moderate size integer long bigger integer float single precision real number double double precision real number
string variable length character string istream input source (e.g., input associated with a file or typed on keyboard) ostream output destination (e.g., output to a file or to a window or screen - line by line)
bool true, false char Enclosed in single quotes: 'a', 'A', 'x', '0', '(' short Typical range: -32768 to 32767 (e.g., not -32769 and not 32768) int Typical range: -2147483648 to 2147483647 long Usually same range as int, but might be bigger float Maximum value usually about 1038 fraction part is 23 bits (for a normalized float) 223 = 8388608. So only about 6 digits can be assumed to be significant. double Maximum value usually about 10307 fraction part is 52 bits (for normalized) 252 = 4503599627370496 (16 digits) So only about 15 digits can be assumed to be significant.
string (No direct representation.) "Hello, World!", string("C++"). The double quoted "Hello, World!" will automatically be converted to type string depending on how it is used. The second example, string("C++"), explicitly requests conversion to type string. istream cin is a predefined input stream associated by default with input typed on the keyboard. It is of type istream. ostream cout is a predefined output stream associated by default with output going to the screen or window (character and line based output).
Variable names may consist of a sequence of letters, digits and underscores.
The first character must be a letter.
There is no limit imposed by C++ on the number of characters in the name of a variable (although some linkers do have limits).
Variable must be declared giving the type, the name, and optionally, an initial value for the variable.
int x; bool result; const double pi = 3.1415926535897932384626433832795; (Note: The const qualifier used in the declaration of the variable pi means that this variable's value cannot be changed. In particular it is illegal to later try to assign a new value to pi.) int i,j,k;
C++ statements are typically terminated by a semicolon. A sequence of statements may, however, be enclosed in {} and treated as a single compound statement.
C++ has a small number of statement types:
x + y; f(x); // call a function f, passing a value x
z = x + y;
if statements: Select one of two choices based on a boolean expression loop statements: for, while, do loops. Repeat a sequence of statements depending on the value of a boolean expression. switch statements: Select one of many choices depending on the value of an integer or character expression.
The assignment operator is '='.
It does not mean equality!
int x = 5; // declaration x = x + 1; // assignment
The value of the right side is computed, then this new value is stored at the memory location associated with the variable on the left side. In this case the new value of x will be 6.
C++ has a large number of predefined operators.
These operators are used to build expressions.
Some expressions have values which can then be assigned to other variables.
Other expressions may have values, but the useful thing about evaluating the expression is any side effects that may occur. These side effects may change the value of some variables without using assignment.
(A useful web site for C++ language reference is: http://www.cppreference.com)
Here are some of the Arithmetic operators in C++ listed from higher precedence to lower. We will learn more about them as the course progresses.
++ -- right * / % left + - left << >> left < <= > >= left == != left = += -= *= /= %= right , left int x = 5; x++; // Side effect is to increment x by 1. int a = 5, b = 3; int c, d; c = a % b; // % is the 'mod' or remainder operator; // c's value is set to 2 d = a/b; // d's value is 1, the integer quotient a += 10; // This is equivalent to a = a + 10;
The insertion operator symbol is <<.
It is used for program output. (The same symbol is also used for a different operator! The types of the operands determine wich operator is meant.)
There are two quite different facilities for program input and output (I/O) in C++. One library, the standard io library is older and was developed for C. A newer library for io was added when C was extended to C++. One sees both libraries in use. In particular, the much of older C style i/o library functionality and similar form has been recently added to Java. Some people find it more convenient (once they have learned how to use it).
The insertion operator is used in the newer C++ I/O library.
The insertion operator is a binary operator.
Its left operand should be of type ostream - output stream.
The right operand can be any of the built in data types such as char, int, float, double, string and can be extended to other data types.
The name cout is predefined of type ostream.
It is associated with a console window or screen output.
int x = 5, y = 10;; const double pi = 3.1415926535897932384626433832795; cout << x; cout << " "; cout << y; cout << " "; cout << pi; Output: 5 10 3.14159 The same result can be obtained by cout << x << " " << y << " " << pi;
Note that the precision for pi got truncated in the output. We will soon see how to better control this.
All of the output in the previous example just accumulated on one output line.
It is easy to generate a 'newline' whenever you like.
One way is to output the newline character.
The newline character, like other character constants is written using single quotes like 'a' or 'b'. However, tabs and newlines do not have character representations so an escape mechanism is used.
The backslash, \ before a character means to "escape" the character's usual meaning in the context.
The newline character is represented using this mechanism as '\n'.
Similarly, '\t' represents the tab character.
The predefined name, endl is NOT a character. It is a slightly more compilicated type. However, inserted using operator<<, it has the same effect as inserting the newline character, '\n' AND also forcing the newline to be output NOW!
So for the most part you can either insert the newline character or endl.
One difference is that the newline character can be included in a literal string:
cout << "Hello, world!\n"; or cout << "Hello, world!" << endl;
The return statement affects the flow of control of execution of statements in a program.
A program code in C++ can be modularized into units: functions, class methods. The return statement sends execution back to the unit that called the current function or class method.
A simple C++ program has the following structure:
1. Optional comments 2. Header file "include" preprocessor statements 3. A function named main containing C++ statements. Program execution begins in this function. ('Optional' means the compiler ignores comments, the instructor does not!)
Here is a sample main function illustrating its required form:
1 int main() 2 { 3 cout << "Hello, World!" << endl; 4 5 return 0; 6 }
At line 5, to what unit is control being returned??
Answer: To the environment or operating system that was used to begin execution. The return value 0 is by convention used to indicate a successful execution. Other values can be used to indicate some sort of failure in the program's effort to carry out its computation. However, the use of this return value is dependent on the environment that executed the program in the first place. Most of the time the environment ignores this return value.
We've seen elementary output using the C++ I/O library. However, there is some additional boilerplate syntax that you will need to remember in order to use cout and the insertion operator without getting compiler errors.
using namespace std; The fully qualified name of cout is std::cout. This is because cout is defined in a C++ unit called a namespace. The particular namespace used for many of the I/O facilities is 'std'. The using clause above avoids your having to write the fully qualified name and simply using 'cout'.
Header files contain declarations.
When a program uses items that are in standard libraries or which are defined in some other user file, a header file is included so that the compiler can see the declaration of this external item.
We need to include a header file for C++ I/O. The name of the file is iostream:
#include <iostream> using namespace std; int main() { ... return 0; }
As noted above, comments should appear at the beginning of every C++ file you write for every C++ program.
There are two styles of comments. The compiler will ignore everything in a comment.
1. Two forward slashes begin a comment that extends to the end of the current line: int count = 0; // This comment extends to end of this line 2. A multiline comment begins with /* and terminates with the first occurence of */ /** * * File: prog1.cpp * * Description: Computes something... * * Created: 03 Jan 08 * Author: */
1 // File: celsius.cpp 2 // Description: Converts Fahrenheit to Celsius 3 // Author: 4 // Last Modified: 07 Sep 05 5 #include <iostream> 6 7 using namespace std; 8 9 int main() 10 { 11 double f, c; 12 13 cout.precision(2); 14 cout.setf(ios::fixed); 15 cout << "Enter fahrenheit temperature: "; 16 cin >> f; 17 c = (f - 32.0) * 5.0/9.0; 18 19 cout << "\n" << f << " degrees fahrenheit is equal to " 20 << c << " degrees celsius." 21 << endl; 22 23 return 0; 24 } 25
Try making some errors on purpose to see what kind of error messages are produced by the compiler you are using.
1 // File: area.cpp 2 // Description: Compute the area of some circles 3 // Author: 4 // Created: 07 Sep 05 5 6 #include <iostream> 7 8 using namespace std; 9 10 int main() 11 { 12 const double pi = 3.1415926535897932384626433832795; 13 double r1 = 1.0, r2 = 1.5; 14 double a1, a2; 15 16 a1 = pi * r1 * r1; 17 a2 = pi * r2 * r2; 18 19 cout.precision(3); 20 cout.setf(ios::fixed); 21 cout.setf(ios::showpoint); 22 23 cout << "A circle of radius " << r1 << " has area " << a1 << endl; 24 cout << "A circle of radius " << r2 << " has area " << a2 << endl; 25 26 27 return 0; 28 } 29 30 Output: A circle of radius 1.000 has area 3.142 A circle of radius 1.500 has area 7.069
1 // File: name.cpp 2 // Description: Changes order of first and last names 3 // Author: 4 // Created: 07 Sep 05 5 6 #include <iostream> 7 #include <string> 8 9 using namespace std; 10 11 int main() 12 { 13 string fname = "Glenn"; 14 string lname = "Lancaster"; 15 16 cout << "\t********************" << endl; 17 cout << "\t* " << lname << ", " << fname << " *" << endl; 18 cout << "\t********************" << endl; 19 20 return 0; 21 } Output: ******************** * Lancaster, Glenn * ********************
1 // File: max.cpp 2 // Description: Computes and prints the maximum of two numbers 3 // Author: 4 // Created: 07 Sep 05 5 6 #include <iostream> 7 #include <cmath> 8 9 using namespace std; 10 11 int main() 12 { 13 double x = 1403.0; 14 15 double a, b, max; 16 17 a = x/2.0; 18 b = sqrt(x); // Square root; sqrt is declared in header file cmath 19 cout.setf(ios::fixed); 20 cout.precision(4); 21 22 if ( a < b) { 23 max = b; 24 } else { 25 max = a; 26 } 27 28 cout << "x = " << x << endl; 29 cout << "x/2 = " << a << endl; 30 cout << "sqrt(x) = " << b << endl; 31 32 if ( a < b) { 33 cout << "The maximum of x/2 and sqrt(x) is sqrt(x)" << endl; 34 } else { 35 cout << "The maximum of x/2 and sqrt(x) is x/2" << endl; 36 } 37 38 return 0; 39 40 } Output: x = 1403.0000 x/2 = 701.5000 sqrt(x) = 37.4566 The maximum of x/2 and sqrt(x) is x/2
These programs would be more useful if the user was able to input the values rather than having them "hard coded".
The extraction operator, >> is part of the C++ I/O library and is used to read input.
This operator is also a binary operator. Its left operand should be of type istream - an input stream. It can be associated either with a file or with the keyboard input.
The right operand should be a variable that can recieve a value from the input. The input is first read as a sequence of characters and then converted to the type of the right operand variable.
The name cin is predefined of type istream.
It is associated by default with keyboard input.
Using the same header file, iostream provides access to both cin and cout.
Fix only the first error (or at most the first 2 errors) before recompiling (rebuilding).
Compilers sometimes appear to give suggestions on fixing errors. These are usually wrong, especially after the first few errors reported.
A missing semicolon at the end of one statement will usually be reported as an error on the next statement. So look at the line before the one the compiler indicates in this case.
1 // File: area2.cpp 2 // Description: Compute the area of some circles with radius 3 // input by the user. 4 // Author: 5 // Created: 07 Sep 05 6 7 #include <iostream> 8 9 using namespace std; 10 11 int main() 12 { 13 const double pi = 3.1415926535897932384626433832795; 14 double r; 15 double a; 16 17 cout << "\nThis program will calcuate the area of a circle" << endl; 18 cout << "\nEnter a value for the radius of a circle: "; 19 cin >> r; 20 21 a = pi * r * r; 22 23 cout.precision(3); 24 cout.setf(ios::fixed); 25 cout.setf(ios::showpoint); 26 27 cout << "A circle of radius " << r << " has area " << a << endl; 28 29 return 0; 30 } 31 32
1 // File: name2.cpp 2 // Description: Changes order of first and last names. Names are input 3 // by the user from the keyboard. 4 // Author: 5 // Created: 07 Sep 05 6 7 #include <iostream> 8 #include <string> 9 10 using namespace std; 11 12 int main() 13 { 14 string fname; 15 string lname; 16 17 cout << "This program prints out your name" 18 << " in a little box."; 19 cout << "\nFirst name: "; 20 cin >> fname; 21 cout << "\nLast name: "; 22 cin >> lname; 23 24 cout << "\nFirst name has length " << fname.length() << endl;; 25 cout << "Last name has length " << lname.length() << endl << endl; 26 27 28 cout << "\t********************" << endl; 29 cout << "\t* " << lname << ", " << fname << " *" << endl; 30 cout << "\t********************" << endl; 31 32 33 return 0; 34 }
Chapters 1 and 2.1 and 2.2 from chapter 2.
Will be posted on the class web site. Due Sep 14.