2621008 - c++ 1
TRANSCRIPT
Slide 1
Slide 2
CompilersThe essential tools needed to follow these tutorials are a computer and a compiler tool chain able to compile C++ code and build the programs to run on it.
Slide 3
What is a compiler?Computers understand only one language and that language consists of sets of instructions made of ones and zeros. This computer language is appropriately called machine language.
A single instruction to a computer could look like this:00000 10011110
A particular computer's machine language program that allows a user to input two numbers, adds the two numbers together, and displays the total could include these machine code instructions:00000 1001111000001 1111010000010 1001111000011 1101010000100 1011111100101 00000000
Compiler
Slide 4
As you can imagine, programming a computer directly in machine language using only ones and zeros is very tedious and error prone. To make programming easier, high level languages have been developed.• This is a portion of code written in C++ that accomplishes
the exact same purpose:int a, b, sum;cin >> a;cin >> b; sum = a + b;cout << sum << endl;
Compiler
Slide 5
Console programs are programs that use text to communicate with the user and the environment, such as printing text to the screen or reading input from a keyboard.
Console programs
Slide 6
What is an algorithm? An algorithm is a clear, concise, and correct step-
by-step sequence of actions used to solve a problem or set of problems
Slide 7
Example Problem For example:
Sorting a stack of papers, each with a number on it
Slide 8
Example 2 Solution
1. Compare the top two papers of the stack; place the smaller valued paper on the bottom of the stack and keep the larger valued paper
2. Grab the next paper off of the top of the stack and compare it to the paper you kept; place the smaller of these two on the bottom of the stack and keep the larger
3. Repeat step 2 until you have reached the (original)bottom of the stack; you should now be holding the largest valued paper in the stack; set this paper aside into a new “sorted stack”
4. Repeat steps 1, 2 & 3, placing the paper from step 3 onto the “sorted stack”, until no more papers remain
Slide 9
Applying algorithms to your coding problems
1. Control Flow Charts - Some programmers prefer to develop drawings showing how information passes from state to state in a solution.
2. Pseudocode – You may develop your own pseudocode language containing all the usual coding constructs of high-level languages and use it to write algorithms to solve your problem.
Slide 10
PROGRAMMING WITH VISUAL C++
WHAT IS THE INTEGRATED DEVELOPMENT ENVIRONMENT?•The integrated development environment (IDE) that comes with Visual C++ 2010 is a completely self - contained environment for creating, compiling, linking, and testing your C++ programs.•The fundamental parts of Visual C++, provided as part of the IDE, are the editor, the compiler, the linker, and the libraries. These are the basic tools that are essential to writing and executing a C++ program.
Slide 11
PROGRAMMING WITH VISUAL C++
The EditorThe editor provides an interactive environment in which to create and edit C++ source code. As well as the usual facilities, such as cut and paste, which you are certainly already familiar with, the editor also provides color cues to differentiate between various language elements.
Slide 12
PROGRAMMING WITH C++
The LinkerThe linker combines the various modules generated by the compiler from source code fi les, adds required code modules from program libraries supplied as part of C++, and welds everything into an executable whole.
Slide 13
C++ programing
Slide 14
PROGRAMMING WITH C++
Phases of C++ programTypical C++ program development has 6 phases:
•Phase 1: Creating a Program
•Phase 2: Preprocessing a C++ Program
•Phase 3: Compiling a C++ Program
•Phase 4: Linking
•Phase 5: Loading
•Phase 6: Execution
Slide 15
PROGRAMMING WITH C++
Phase 1: Creating a Program
Phase 1 consists of editing a file with an editor program, normally known simply as an editor. You type a C++ program (typically referred to as source code) using the editor, make any necessary corrections and save the program on a secondary storage device, such as your hard drive.
Slide 16
PROGRAMMING WITH C++
Phase 2: Preprocessing a C++ Program
In a C++ system, a preprocessor program executes automatically before the compiler’s translation phase begins. The C++ preprocessor obeys commands called preprocessor directives, which indicate that certain manipulations are to be performed on the program before compilation. These manipulations usually include other text files to be compiled, and perform various text replacements.
Slide 17
PROGRAMMING WITH C++
Phase 3: Compiling a C++ Program
In Phase 3, the compiler translates the C++ program into machine-language code
Slide 18
PROGRAMMING WITH C++
Phase 4: Linking
Phase 4 is called linking. C++ programs typically contain references to functions and data defined elsewhere, such as in the standard libraries or in the private libraries of groups of programmers working on a particular project. A linker links the object code with the code for the missing functions to produce an executable program.
Slide 19
PROGRAMMING WITH C++
Phase 5: Loading
Before a program can be executed, it must first be placed in memory. This is done by the loader, which takes the executable image from disk and transfers it to memory.
Slide 20
PROGRAMMING WITH C++
Phase 6: Execution
Finally, the computer, under the control of its CPU, executes the program one instruction at a time.
Slide 21
A sample of program in C++:
Preprocessor Directives
Slide 22
C++ source code is pre-processed before it is compiled into object Code. A preprocessor directive, which begins with a # sign (such as #include, #define), tells the preprocessor to perform a certain action (such as including a header file, or performing text replacement), before compiling the source code into object code. Preprocessor directives are not programming statements, and therefore should NOT be terminated with a semi-colon.
Slide 23
PROGRAMMING WITH VISUAL C++
In almost all of the C++ programs, we use #include <iostream> to include the input/output stream library header into our program, so as to use the IO library function to carry out input/output operations (such as cin and cout).
For example,
Slide 24
PROGRAMMING WITH VISUAL C++
Comments
Comments are used to document and explain your codes and program logic. Comments are not programming statements and are ignored by the compiler, but they VERY IMPORTANT for providing documentation and explanation for others to understand your program (and also for yourself three days later).
There are two kinds of comments in C/C++:1.Multi-line Comment: begins with a /* and ends with a */, and can span several lines.2.End-of-line Comment: begins with // and lasts till the end of the current line.
Slide 25
PROGRAMMING WITH VISUAL C++
The mainmain Function
Following the preprocessor directive(s) is the body of the program characterized by the function main().
• The execution of a C++ program always starts here. • It is a standardized convention that function main() main() is
declared with an int int preceding it. • intint is the return value type of the function main()main().• The parentheses after main indicate that main is a
program building block called a functionfunction.
Slide 26
Declaration of variables
Variable DeclarationsIn C++ before use of any variables you should declare it. This means Variable Declaration. For example we want to write a program that add two numbers. In this case we should declare three variables. The type off variable is important.
For example:int a;float mynumber;
Declaration of variables
int a, b, c;
Slide 27
If declaring more than one variable of the same type, they can all be declared in a single statement by separating their identifiers with commas.
For example:
To see what variable declarations look like in action within a program, let's have a look at the entire C++ code in the next slide:
Declaration of variables
Slide 28
// operating with variables#include <iostream>using namespace std;int main (){ // declaring variables: int a, b; int result; // process: a = 5; b = 2; a = a + 1; result = a - b; // print out the result: cout << result; // terminate the program: return 0;}
Don't be worried if something else than the variable declarations themselves look a bit strange to you. Most of it will be explained in more detail in coming chapters.
Initialization of variables
Slide 29
When the variables in the example above are declared, they have an undetermined value until they are assigned a value for the first time. But it is possible for a variable to have a specific value from the moment it is declared. This is called the initialization of the variable.
For example, to declare a variable of type int called x and initialize it to a value of zero from the same moment it is declared, we can write:
int x = 0;A second method, known as constructor initialization (introduced by the C++ language), encloses the initial value between parentheses (()):
type identifier (initial_value); For example:
int x (0);
Copyright © 2003 Pearson Education, Inc. Slide 30
Finally, a third method, known as uniform initialization, similar to the above, but using curly braces ({}) instead of parentheses (this was introduced by the revision of the C++ standard, in 2011):
type identifier {initial_value}; For example:
int x {0};
Slide 31
All three ways of initializing variables are valid and equivalent in C++.
// initialization of variables#include <iostream>using namespace std;int main (){ int a=5; // initial value: 5 int b(3); // initial value: 3 int c{2}; // initial value: 2 int result; // initial value undetermined a = a + b; result = a - c; cout << result;
return 0;}
Type deduction: auto and decltype
Slide 32
When a new variable is initialized, the compiler can figure out what the type of the variable is automatically by the initializer. For this, it suffices to use auto as the type specifier for the variable:
int foo = 0;auto bar = foo; // the same as: int bar = foo;
Here, bar is declared as having an auto type; therefore, the type of bar is the type of the value used to initialize it: in this case it uses the type of foo, which is int.
Variables that are not initialized can also make use of type deduction with the decltype specifier:
int foo = 0;decltype(foo) bar; // the same as: int bar;
Slide 33
PROGRAMMING WITH VISUAL C++
Variable Types
Slide 34
variables
In the last example we want to use integer numbers so we should to define them before using in our program.Simply we consider ‘Number 1’ as first and ‘Number 2’ as second and ‘Sum’ as third number. So for declaration these number we have:
int number1; // first integer to addint number2; // second integer to addint sum; // sum of number1 and number2
Slide 35
Naming variables Or Identifier
• Naming variables appropriately is important for writing good, understandable, and maintainable code.
• Variable names can be alphanumeric, but they cannot start with a number.
• They cannot contain spaces and cannot contain arithmetic operators (such as +, –, and so on) within them.
• You can elongate variable names using an underscore. • Variables names also cannot be reserved keywords. For example, a
variable named return causes compilation failures.
Slide 36
1)A variable has a name (or identifier), e.g., radius, area, age, height. The name is needed to uniquely identify each variable, so as to assign a value to the variable (e.g., radius=1.2), and retrieve the value stored (e.g., area = radius*radius*3.1416).2)A variable has a type. Examples of type are,
1) int: for integers (whole numbers) such as 123 and -456;2) double: for floating-point or real numbers such as 3.1416, -
55.66, having a decimal point and fractional part.3)A variable can store a value of that particular type. It is important to take note that a variable in most programming languages is associated with a type, and can only store value of the particular type. For example, a int variable can store an integer value such as 123, but NOT real number such as 12.34, nor texts such as "Hello".4)The concept of type was introduced into the early programming languages to simplify interpretation of data made up of 0s and 1s. The type determines the size and layout of the data, the range of its values, and the set of operations that can be applied.
variables
Assignment operator (=)
Slide 37
The assignment operator assigns a value to a variable.
x = 5;This statement assigns the integer value 5 to the variable x. For example, let's have a look at the following code - I have included the evolution of the content stored in the variables as comments: // assignment operator#include <iostream>using namespace std;int main (){ int a, b; // a:?, b:? a = 10; // a:10, b:? b = 4; // a:10, b:4 a = b; // a:4, b:4 b = 7; // a:4, b:7 cout << "a:"; cout << a; cout << " b:"; cout << b;}
Arithmetic operators ( +, -, *, /, % )
Slide 38
The five arithmetical operations supported by C++ are:
operator description
+ addition
- subtraction
* multiplication
/ division
% modulo
Operations of addition, subtraction, multiplication and division correspond literally to their respective mathematical operators. The last one, modulo operator, represented by a percentage sign (%), gives the remainder of a division of two values. For example:
x = 11 % 3;results in variable x containing the value 2, since dividing 11 by 3 results in 3, with a remainder of 2.
Compound assignment
Copyright © 2003 Pearson Education, Inc. Slide 39
(+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=)Compound assignment operators modify the current value of a variable by performing an operation on it. They are equivalent to assigning the result of an operation to the first operand:
expression equivalent to...
y += x; y = y + x;
x -= 5; x = x - 5;
x /= y; x = x / y;
price *= units + 1; price = price * (units+1);
Slide 40
and the same for all other compound assignment operators. For example:
// compound assignment operators#include <iostream>using namespace std;int main (){ int a, b=3; a = b; a+=2; // equivalent to a=a+2 cout << a;}
Increment and decrement (++, --)
Slide 41
Some expression can be shortened even more: the increase operator (++) and the decrease operator (--) increase or reduce by one the value stored in a variable. They are equivalent to +=1 and to -=1, respectively. Thus:
++x;x+=1;x=x+1;
Example 1 Example 2
x = 3;y = ++x;// x contains 4, y contains 4
x = 3;y = x++;// x contains 4, y contains 3
Slide 42
PROGRAMMING WITH VISUAL C++
An Output Statement
• Every C++ statement must end with a semicolon (also known as the statement terminator).
Slide 43
PROGRAMMING WITH VISUAL C++
The std Namespace
The coutcout is defined in stdstd namespace. When we want to use the coutcout we should make clear that coutcout is located in stdstd namespace.
Many programmers find it tedious to repeatedly add the stdstd namespace specifier to their code when using coutcout and other such features contained in the same. The using namespace declaration will help you avoid this repetition.
Slide 44
PROGRAMMING WITH VISUAL C++
1
2
Slide 45
PROGRAMMING WITH VISUAL C++
Ex: The escape sequence \n means newline.
Slide 46
PROGRAMMING WITH VISUAL C++
Returning a Value Functions in C++ need to return a value unless explicitly specified otherwise.
main() main() is a function, too, and always returns an integer.
Slide 47
PROGRAMMING WITH VISUAL C++
Printing Multiple Lines of Text with a Single Statement
Slide 48
Another C++ Program: Adding Integers
Another C++ Program: Adding IntegersOur next program uses the input stream object std::cin and the stream extraction operator, >>, to obtain two integers typed by a user at the keyboard, computes the sum of these values and outputs the result using std::cout.
Introduction to strings
Slide 49
Fundamental types represent the most basic types handled by the machines where the code may run. But one of the major strengths of the C++ language is its rich set of compound types, of which the fundamental types are mere building blocks.
An example of compound type is the string class. Variables of this type are able to store sequences of characters, such as words or sentences.For use of string type the program needs to include the header where the type is defined within the standard library (header <string>):
// my first string#include <iostream>#include <string>using namespace std;
int main (){ string mystring; mystring = "This is a string"; cout << mystring; return 0;}
Introduction to strings
Slide 50
As you can see in the previous example, strings can be initialized with any valid string literal, just like numerical type variables can be initialized to any valid numerical literal. As with fundamental types, all initialization formats are valid with strings:
string mystring = "This is a string";string mystring ("This is a string");string mystring {"This is a string"};
constant expressions
Slide 51
Sometimes, it is just convenient to give a name to a constant value:
const double pi = 3.1415926;const char tab = '\t';
We can then use these names instead of the literals they were defined to:
#include <iostream>using namespace std;const double pi = 3.14159;const char newline = '\n';int main (){ double r=5.0; // radius double circle; circle = 2 * pi * r; cout << circle; cout << newline;}
Preprocessor definitions (#define)
Slide 52
Another mechanism to name constant values is the use of preprocessor definitions. They have the following form:
#define identifier replacement
#include <iostream>using namespace std;#define PI 3.14159#define NEWLINE '\n'int main (){ double r=5.0; // radius double circle;
circle = 2 * PI * r; cout << circle; cout << NEWLINE;}
Note that the #define lines are preprocessor directives, and as such are single-line instructions that -unlike C++ statements- do not require semicolons (;) at the end.
Explicit type casting operator
Slide 53
Type casting operators allow to convert a value of a given type to another type. There are several ways to do this in C++. The simplest one, which has been inherited from the C language, is to precede the expression to be converted by the new type enclosed between parentheses (()):
int i;float f = 3.14;i = (int) f;
The previous code converts the floating-point number 3.14 to an integer value (3);
Another way to do the same thing in C++ is to use the functional notation preceding the expression to be converted by the type and enclosing the expression between parentheses:
i = int (f);
sizeof
Slide 54
This operator accepts one parameter, which can be either a type or a variable, and returns the size in bytes of that type or object:
x = sizeof (char);
swap()
Slide 55
Function swap() is a C++ Standard Library function. It exchanges the values of two variables. The variables should be of same type. See the following program for illustration.
#include <iostream>using namespace std;int main(){//swap function interchanges the values of same type variablesint x ,y;cout<<"Write two integers x = ";cin>>x; cout<<" and y = "; cin>>y;swap(x,y);cout <<"After swapping: x = "<<x <<" and y = "<< y<<endl;return 0;}
Slide 56