Date post: | 15-Apr-2017 |
Category: |
Engineering |
Upload: | hnde-labuduwa-galle |
View: | 19 times |
Download: | 0 times |
Information Technology III
Introduction to Programming with C++
2 History of C and C++ History of C++
Extension of C Early 1980s: Bjarne Stroustrup (Bell Laboratories)
Provides capabilities for object-oriented programming Objects: reusable software components
Model items in real world Object-oriented programs
Easy to understand, correct and modify Hybrid language
C-like style Object-oriented style Both
3 Basics of a Typical C++ Environment
C++ systems Program-development environment Language C++ Standard Library
4 Basics of a Typical C++ EnvironmentPhases of C++ Programs:
1. Edit2. Preprocess3. Compile4. Link5. Load6. Execute
LoaderPrimaryMemory
Program is created inthe editor and stored
on disk.Preprocessor programprocesses the code.
Loader puts programin memory.
CPU takes eachinstruction and
executes it, possiblystoring new data
values as the programexecutes.
CompilerCompiler creates
object code and storesit on disk.
Linker links the objectcode with the libraries,
creates a.out andstores it on disk
Editor
Preprocessor
Linker
CPU
PrimaryMemory
.
.
.
.
.
.
.
.
.
.
.
.
Disk
Disk
Disk
Disk
Disk
Hello WorldThis is a comment line - the line is a brief description of program does.
directives for the preprocessor. They are not executable code lines but indications for the compiler.
<iostream.h> tells the compiler's preprocessor to include the iostream standard header file.
cout is the standard output stream
The return instruction causes the main() function finish and return the code terminating the program without any errors during its execution
This line corresponds to the beginning of the main function declaration. The main function is the point C++ programs begin their execution. It is first to be executed when a program starts.
6 Basics of a Typical C++ Environment Input/output
cin Standard input stream Normally keyboard
cout Standard output stream Normally computer screen
cerr Standard error stream Display error messages
Comments
It is of 2 types:-
Single line comments // example of single line comment//this is the very simple example of single line comments
Multi line comments/*This is the example ofmulti line comment*/
8 A Simple Program: Printing a Line of Text
Escape Sequence Description
\n Newline. Position the screen cursor to the beginning of the next line.
\t Horizontal tab. Move the screen cursor to the next tab stop.
\r Carriage return. Position the screen cursor to the beginning of the current line; do not advance to the next line.
\a Alert. Sound the system bell. \\ Backslash. Used to print a backslash character. \" Double quote. Used to print a double quote
character.
9 Variables Variable names
Valid identifier Series of characters (letters, digits, underscores) Cannot begin with digit Case sensitive length of an identifier is not limited, (but some compilers
only the 32 first characters rest ignore) Neither spaces nor marked letters can be part of an
identifier can also begin with an underline character ( _ ) your own identifiers cannot match any key word of the C++
language
10 Variables Location in memory where value can be stored
Common data types int - integer numbers char - characters double - double precision floating point numbers Float - floating point numbers Bool - Boolean value (true or false)
Signed and Unsigned Integer Types
For integer data types, there are three sizes: Int long - larger size of integer, short, which are declared as long int and short int.
The keywords long and short are called sub-type qualifiers.
The requirement is that short and int must be at least 16 bits, long must be at least 32 bits,
short is no longer than int, which is no longer than long.
Typically, short is 16 bits, long is 32 bits, and int is either 16 or 32 bits.
all integer data types are signed data types, i.e. they have values which can be positive or negative
Declaration of variables Declare variables with name and data type before use
int a; float mynumber; int MyAccountBalance;
int integer1;int integer2;int sum;
int integer1, integer2, sum;
Example A program to add two numbers;
#include<iostream>
using namespace std;
int main() {
int a, b; // variable declaration
a = 10;
b= 20;
int addition = a + b;
cout << “answer is:” << addition << endl;
return 0;
}
Scope of variablesGlobal variables can be referred to anywhere in the code, within any function, whenever it is after its declaration.
The scope of the local variables is limited to the code level in which they are declared.
Constants: Literals
A constant is any expression that has a fixed value.
It can be Integer Numbers, Floating-Point Numbers, Characters and Strings
Examples 75 // decimal 0113 // octal 0x4b // hexadecimal 6.02e23 // 6.02 x 10 23
1.6e-19 // 1.6 x 10 -19
3.0 // 3.0 #define PI 3.14159265 #define NEWLINE '\n'
circle = 2 * PI * r; cout << NEWLINE;
Defined constants (#define) You can define your own names for constants simply by using the
#define preprocessor directive. #define identifier value
Example #define PI 3.14159265 #define NEWLINE '\n' #define WIDTH 100
17 Operators Input stream object
>> (stream extraction operator) Used with std::cin Waits for user to input value, then press Enter (Return) key Stores value in variable to right of operator
Converts value to variable data type
= (assignment operator) Assigns value to variable Binary operator (two operands) Example:
sum = variable1 + variable2;
Arithmetic operators The five arithmetical operations
+ addition - subtraction * multiplication / division % module
Example int a, b; a = 10; b = 4; a = b; b = 7; a = 2 + (b = 5); a = b = c = 5; a -= 5;
a /= b; a++; a+=1; a=a+1; B=3; A=++B; A=B++;
Relational operators == Equal != Different > Greater than < Less than >= Greater or equal than <= Less or equal than
(7 == 5) (5 > 4) (3 != 2) (6 >= 6)
Suppose that a=2, b=3and c=6, (a == 5) (a*b >= c) (b+4 > a*c) ((b=2) == a)
Logic operators ( !, &&, || ) For example:
( (5 == 5) && (3 > 6) ) ( (5 == 5) || (3 > 6))
Conditional operator ( ? ) condition ? result1 : result2 if condition is true the expression will return result1, if not it
will return result2. 7==5 ? 4 : 3 7==5+2 ? 4 : 3 5>3 ? a : b
22 Precedence of Operators Rules of operator precedence
Operators in parentheses evaluated first Nested/embedded parentheses
Operators in innermost pair first Multiplication, division, modulus applied next
Operators applied from left to right Addition, subtraction applied last
Operators applied from left to rightOperator(s) Operation(s) Order of evaluation (precedence)
() Parentheses Evaluated first. If the parentheses are nested, the expression in the innermost pair is evaluated first. If there are several pairs of parentheses “on the same level” (i.e., not nested), they are evaluated left to right.
*, /, or % Multiplication Division Modulus
Evaluated second. If there are several, they re evaluated left to right.
+ or - Addition Subtraction
Evaluated last. If there are several, they are evaluated left to right.
Types of Errors Syntax errors
A syntax error occurs when the programmer fails to obey one of the grammar rules of the language.
Runtime errorsA runtime error occurs whenever the program instructs the computer to do something that it is either incapable or unwilling to do.
Logic errorsLogic errors are usually the most difficult kind of errors to find and fix, because there frequently is no obvious indication of the error. Usually the program runs successfully. It simply doesn't behave as it should. it doesn't produce the correct answers.
Syntax errors
Syntax Error: undeclared identifer “cout”
Syntax errors result = (firstVal - secondVal / factor;
Syntax Error: ’)’ expected
cout << “Execution Terminated << endl;
Syntax Error: illegal string constant
double x = 2.0, y = 3.1415, product;
x * y = product;
Syntax Error: not an l-value
Logical errors int a, b;
int sum = a + b;
cout << "Enter two numbers to add: ";
cin >> a; cin >> b;
cout << "The sum is: " << sum;
char done = 'Y';
while (done = 'Y') {
//... cout << "Continue? (Y/N)";
cin >> done;
}