730 likes | 932 Views
Introduction to C++ Programming. Introduction. The C++ language will be used as a tool to learn about programming You will learn how to write structured C++ programs Object-oriented aspects of C++ (objects, templates, etc) will NOT be covered until CS432. C++ Programming Concepts.
E N D
Introduction • The C++ language will be used as a tool to learn about programming • You will learn how to write structured C++ programs • Object-oriented aspects of C++ (objects, templates, etc) will NOT be covered until CS432
C++ Programming Concepts • To write a C++ program, we need: • Text editor • C++ compiler • Bloodshed Dev-C++ contains an editor and a compiler in one • This is known as an IDE (Integrated Development Environment)
Running C++ Programs • Use an editor to create/edit C++ code in a text file • C++ filenames ended with extension .cpp • Compile and link the C++ file • Execute the executable file created • If find bugs or errors, go back to the first step and correct them and try again.
A Simple C++ program: #include <iostream> using namespace std; //Displays greeting int main() { cout << "Hello World!"; return 0; } (Each line is explained on the following slides)
A Simple C++ program: #include <iostream> using namespace std; //Displays greeting int main() { cout << "Hello World!"; return 0; } Tells compiler to include code from the iostream library for use of input and output routines.
A Simple C++ program: #include <iostream> using namespace std; //Displays greeting int main() { cout << "Hello World!"; return 0; } Tells compiler to use a standard environment. (The first 2 lines must appear in ALL your programs)
A Simple C++ program: #include <iostream> using namespace std; //Displays greeting int main() { cout << "Hello World!"; return 0; } Comment for the programmer – lines beginning with "//" are ignored by the compiler
A Simple C++ program: Note Your text uses: void main() but our compiler requires: int main() and the return of an integer. #include <iostream> using namespace std; //Displays greeting int main() { cout << "Hello World!"; return 0; } C++ programs are built using functions. A C++ program must contain at least one function, called main. This is the main function “header”.
A Simple C++ program: #include <iostream> using namespace std; //Displays greeting int main() { cout << "Hello World!"; return 0; } Left curly brace marks beginning and right curly brace marks end of the main function
A Simple C++ program: #include <iostream> using namespace std; //Displays greeting int main() { cout << "Hello World!"; return 0; } cout displays output, in this case, Hello World! to the monitor
A Simple C++ program: #include <iostream> using namespace std; //Displays greeting int main() { cout << "Hello World!"; return 0; } return tells the program to exit from the main function. By default, returning 0 implies success.
A Simple C++ program:Sample Run When the program is executed, this is the output:
Identifiers • Identifiers are the words that a programmer uses to name things in a program • An identifier can be made up of letters, digits, and the underscore character • An identifier cannotbegin with a digit • C++ is case sensitive, therefore num and Num are different identifiers • Keywords CANNOT be identifiers (see next slide)
Keywords C++ keywords (do NOT use as Identifiers) : asm auto bool break case catch char class const const_cast continue default delete do double dynamic-cast else enum explicit extern FALSE float for friend goto if int long mutable namespace new operator private register return Short signed sizeof static static-cast struct switch template this throw try TRUE typedef typeid typename union unsigned using virtual void volatile wchar_t while
Data • You can store each piece of program data as: • a Constant or • a Variable • You will assign an identifier (name) to: • each constant • each variable
Data Types Each piece of data stored in a program must also have a type. Three basic C++ data types are: • int- whole numbers // No commas or leading zeros in number • double- numbers with fractional parts // Has a decimal point • char- a single ASCII character // Enclosed in single quotes
Variables • Variables are containers used to hold • input data • intermediate data • output data in your program (think of them as named chunks of memory) • A variable will occupy a number of bytes in Main Memory • The number of bytes allocated to a variable depends on the type of data that will be stored in it (e.g. numbers, characters, etc.)
Declaring Variables • Declaring a variable will: - define its type - reserve a memory cell for it - give the memory cell a name (an identifier) Format: type variable-list; Examples: char initial; int num, count; double gpa;
Memory variable name(s) data type numStudents: 9200 9204 9208 9212 9216 9220 9224 9228 9232 double total; … average: int average, max; max: total: Variables in Memory int numStudents; … The value stored in a variable is initially garbage, and changes as the program runs.
Constants • A constant is similar to a variable, except that its value is set by the programmer and CANNOT change • The compiler will issue an error if you try to modify a constant • Why use constants? • Gives names to otherwise unclear literal values • Facilitates easier changes to the code • Prevents inadvertent errors
Declaring Constants • Declaring a constant will: - define its type and reserve a memory cell for it - give the memory cell a name (an identifier) - store a value in the memory cell • Since the value is set by the programmer, the value must be known when the program is written Format: const type constant-name = value; Examples: const double PI = 3.14; const int AGE = 33; const char YES = 'Y';
constant name Memory data type constant value 6200 6204 6208 6212 6216 6220 6224 6228 6232 const int DOZEN = 12; … 12 DOZEN: const double PI = 3.14; 3.14 PI: Constants in Memory The value stored in a constant CANNOT change as the program runs.
Declaring Constants/Variables • Declare constants and variables at the top of the main function • Use good identifiers to make code "Self-Documenting" • Follow the identifier rules: • Should begin with a letter, followed by letters, digits and underscores • Are case-sensitive. Standard conventions are: • Variable identifiers should begin with a lowercase letter • Constants identifiers should be ALL uppercase
Constants/Variables Example #include <iostream> using namespace std; int main() { const char INITIAL = ‘P’; int num; : Constant INITIAL and variable num are declared at the top of the main function
Comments There are two types of C++ comments: • Single-line comments use //… // This comment runs to the end of the current line • Multi-lines comments use /* … */ /* This comment runs to the ending symbol, even onto new lines */ Comments are ignored by the compiler.
Function Statements • Function statements are located between the function’s curly braces ''{" and "}" • Statements are separated by semicolons (;) • Statements can take up more than one line • Extra blanks are ignored - used for readability
Memory count: 0 num: 55 ltr: A Assignment Statements • An assignment statement changes the value of a variable • The assignment operator is the = sign int count, num; char ltr; count = 0; num = 55; ltr = ‘A’; • The value on the right is stored in the variable on the left • Any value that was in the variable is overwritten
Memory max: 50 count: 0 Assignment Statements • You can only assign a value to a variable that is compatible with the variable's declared type • You can declare a variable and assign an initial value to it at the same time: int count = 0; int max = 50; This is called “initializing” a variable
Arithmetic Expressions • An expression is a combination of operators and operands • Arithmetic expressions compute numeric results using arithmetic operators: Addition + Subtraction - Multiplication * Division / Remainder %
Operator Results • Arithmetic operators can be used with any numeric type • An operand is a number or variable used by the operator • Result of an operator depends on the types of operands • If both operands are int, the result is int • If one or both operands are double, the result is double
Division and Remainder • If both operands to the division operator (/) are integers, the result is an integer (the fractional part is discarded) 14 / 3 equals? 4 8 / 12 equals? 0 • The modulus operator (%) returns the remainder after dividing the second operand into the first (both operands must be integers) 14 % 3 equals? 2 8 % 12 equals? 8
Operator Precedence • Operators can be combined into complex expressions: result = total + count / max - offset; • Precedence rules (same as default math rules) • Parenthesis are done first • Division, multiplication and modulus are done second (left to right) • Addition and subtraction are done last (left to right)
Assignment Revisited • You can consider assignment as another operator, with a lower precedence than the arithmetic operators First the expression on the right hand side of the = operator is evaluated, in precedence order answer = sum / 4 + MAX * lowest; 4 1 3 2 Then the result is stored in the variable on the left hand side
Memory count: 8 Assignment Revisited • The right and left hand sides of an assignment statement can contain the same variable count = 8; First, 20 is added to the original value of count count = count + 20; 28 Then the result is stored back into count (overwriting the original value)
Spacing • Use spacing to make arithmetic assignment statements more readable! • Which is easier to read? ans=num1+num2*num3; or ans = num1 + num2 * num3;
Arithmetic Equivalencies • Mathmatical Formulas: • c = a2 + b2 • num = 1 x(x+y) • C++ Equivalent Expressions: • c = (a * a) + (b * b); • num = 1 / ( x * (x + y));
Compound Assignment Operators • Compound assignment operators are operators which provide a shortcut when adding, subtracting, multiplying, or dividing a number to/by itself. • Operators: += -= *= /= %= A op= B is the same as A = A op B A += B A = A + B A -= B A = A - B A *= B A = A * B A /= B A = A / B A %= B A = A % B
Increment/Decrement Operators • The increment operator (++) adds one to the value of the variable. The decrement operator (--) subtracts one from the value of the variable. x++; ++x; // both increase x by 1 x--; --x; // both decrease x by 1 • When used alone with one variable, the following three statements are equivalent: x++; ++x; x = x + 1;
Increment/Decrement Operators • When used within an expression, however, the placement matters. • ++ (pre-increment operator) when the ++ is placed on the left-hand side of a variable (++x). Variable is incremented BEFORE the rest of expression is evaluated: A = ++B * Num; is equivalent to: B = B + 1; A = B * Num;
Increment/Decrement Operators -- (pre-decrement operator) When the -- is placed on the left-hand side of a variable (--x). Variable is decremented BEFORE the rest of expression is evaluated: A = --B * Num; is equivalent to: B = B - 1; A = B * Num;
Increment/Decrement Operators • ++ (post-increment operator) when the ++ is placed on the right-hand side of a variable (x++). Variable is incremented AFTER the rest of expression is evaluated: A = B++ * Num; is equivalent to A = B * Num;B = B + 1;
Increment/Decrement Operators • -- (post-decrement operator) when the -- is placed on the right-hand side of a variable (x--). Variable is decremented AFTER the rest of expression is evaluated: A = B-- * Num; is equivalent to A = B * Num; B = B - 1;
Input/Output (I/O) • We use two input/output statements • one for output (cout) • one for input (cin) • In any program that uses these statements, you must have the following lines at the very beginning of the code: #include <iostream> using namespace std;
Output Statement cout– writes output to the monitor Format: cout << field1 << field2 << ... << fieldN; A field can be: - a string of characters (text) in double quotes - a variable - endl (end line/new line)
Output Example Example Code: cout << "Hello" << endl; sum = 10; cout << "Sum is " << sum << endl; cout << "Enter a number:"; Resulting Output: Hello Sum is 10 Enter a number:
Input Statement cin- gets input from the keyboard (typed in by the user) Format: cin >> field; Here the fieldmust be a variable name
Memory pay: 9.50 Input Example Example:cout << "Enter pay amount: "; cin >> pay; Resulting Output:Enter pay amount: 9.50 cinstores the number typed at keyboard (9.50) into the variable pay in memory
I/O Stream: Output • Escape sequences: \" to display a double quote \t to display a tab \\ to display a backslash \a to cause computer to beep
I/O Stream: Output • Formatting: • Must include iomanip library to use functions: • setprecision(n) - sets number of decimal places displayed • setw(n) - sets width of output • Example: float num = 4.557; cout << setprecision(1) << setw(5) << num; Result: displays 4.6 with two leading spaces 4.6