SlideShare a Scribd company logo
1 of 56
Slide 1
Slide 2
Compilers
The 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 10011110
00001 11110100
00010 10011110
00011 11010100
00100 10111111
00101 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 Editor
The 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 Linker
The 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++ program
Typical 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 intint 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 Declarations
In 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 add
int number2; // second integer to add
int 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 Integers
Our 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 variables
int 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

More Related Content

What's hot (20)

Programming in c notes
Programming in c notesProgramming in c notes
Programming in c notes
 
Computer programming chapter ( 3 )
Computer programming chapter ( 3 ) Computer programming chapter ( 3 )
Computer programming chapter ( 3 )
 
Lecture 1
Lecture 1Lecture 1
Lecture 1
 
Computer programming chapter ( 4 )
Computer programming chapter ( 4 ) Computer programming chapter ( 4 )
Computer programming chapter ( 4 )
 
C++ Tutorial
C++ TutorialC++ Tutorial
C++ Tutorial
 
Abc c program
Abc c programAbc c program
Abc c program
 
C_Programming_Notes_ICE
C_Programming_Notes_ICEC_Programming_Notes_ICE
C_Programming_Notes_ICE
 
C language
C languageC language
C language
 
Problem solving methodology
Problem solving methodologyProblem solving methodology
Problem solving methodology
 
Srgoc dotnet_new
Srgoc dotnet_newSrgoc dotnet_new
Srgoc dotnet_new
 
C language
C languageC language
C language
 
C and C++ Industrial Training Jalandhar
C and C++ Industrial Training JalandharC and C++ Industrial Training Jalandhar
C and C++ Industrial Training Jalandhar
 
C & C++ Training Centre in Ambala! BATRA COMPUTER CENTRE
C & C++ Training Centre in Ambala! BATRA COMPUTER CENTREC & C++ Training Centre in Ambala! BATRA COMPUTER CENTRE
C & C++ Training Centre in Ambala! BATRA COMPUTER CENTRE
 
Overview of c
Overview of cOverview of c
Overview of c
 
C notes
C notesC notes
C notes
 
SULTHAN's - C Programming Language notes
SULTHAN's - C Programming Language notesSULTHAN's - C Programming Language notes
SULTHAN's - C Programming Language notes
 
Programming in c
Programming in cProgramming in c
Programming in c
 
A tutorial on C++ Programming
A tutorial on C++ ProgrammingA tutorial on C++ Programming
A tutorial on C++ Programming
 
Intro
IntroIntro
Intro
 
Introduction to C Programming
Introduction to C ProgrammingIntroduction to C Programming
Introduction to C Programming
 

Similar to 2621008 - C++ 1

Introduction-to-C-Part-1 (1).doc
Introduction-to-C-Part-1 (1).docIntroduction-to-C-Part-1 (1).doc
Introduction-to-C-Part-1 (1).docMayurWagh46
 
Introduction-to-C-Part-1.pptx
Introduction-to-C-Part-1.pptxIntroduction-to-C-Part-1.pptx
Introduction-to-C-Part-1.pptxNEHARAJPUT239591
 
Introduction-to-C-Part-1 JSAHSHAHSJAHSJAHSJHASJ
Introduction-to-C-Part-1 JSAHSHAHSJAHSJAHSJHASJIntroduction-to-C-Part-1 JSAHSHAHSJAHSJAHSJHASJ
Introduction-to-C-Part-1 JSAHSHAHSJAHSJAHSJHASJmeharikiros2
 
Introduction to cpp language and all the required information relating to it
Introduction to cpp language and all the required information relating to itIntroduction to cpp language and all the required information relating to it
Introduction to cpp language and all the required information relating to itPushkarNiroula1
 
Introduction-to-C-Part-1.pdf
Introduction-to-C-Part-1.pdfIntroduction-to-C-Part-1.pdf
Introduction-to-C-Part-1.pdfAnassElHousni
 
C++ helps you to format the I/O operations like determining the number of dig...
C++ helps you to format the I/O operations like determining the number of dig...C++ helps you to format the I/O operations like determining the number of dig...
C++ helps you to format the I/O operations like determining the number of dig...bhargavi804095
 
ch01_an overview of computers and programming languages
ch01_an overview of computers and programming languagesch01_an overview of computers and programming languages
ch01_an overview of computers and programming languagesLiemLe21
 
Lecture-1&2.pdf Visual Programming C# .net framework
Lecture-1&2.pdf Visual Programming C# .net frameworkLecture-1&2.pdf Visual Programming C# .net framework
Lecture-1&2.pdf Visual Programming C# .net frameworkAbdullahNadeem78
 
C++ was developed by Bjarne Stroustrup, as an extension to the C language. cp...
C++ was developed by Bjarne Stroustrup, as an extension to the C language. cp...C++ was developed by Bjarne Stroustrup, as an extension to the C language. cp...
C++ was developed by Bjarne Stroustrup, as an extension to the C language. cp...bhargavi804095
 
C++ In One Day_Nho Vĩnh Share
C++ In One Day_Nho Vĩnh ShareC++ In One Day_Nho Vĩnh Share
C++ In One Day_Nho Vĩnh ShareNho Vĩnh
 
Fundamentals of programming with C++
Fundamentals of programming with C++Fundamentals of programming with C++
Fundamentals of programming with C++Seble Nigussie
 
How to work with code blocks
How to work with code blocksHow to work with code blocks
How to work with code blocksTech Bikram
 
CIS 170 Life of the Mind/newtonhelp.com   
CIS 170 Life of the Mind/newtonhelp.com   CIS 170 Life of the Mind/newtonhelp.com   
CIS 170 Life of the Mind/newtonhelp.com   llflowe
 
CIS 170 Imagine Your Future/newtonhelp.com   
CIS 170 Imagine Your Future/newtonhelp.com   CIS 170 Imagine Your Future/newtonhelp.com   
CIS 170 Imagine Your Future/newtonhelp.com   bellflower42
 
C++ language basic
C++ language basicC++ language basic
C++ language basicWaqar Younis
 
Basics of C Lecture 2[16097].pptx
Basics of C Lecture 2[16097].pptxBasics of C Lecture 2[16097].pptx
Basics of C Lecture 2[16097].pptxCoolGamer16
 

Similar to 2621008 - C++ 1 (20)

Introduction-to-C-Part-1 (1).doc
Introduction-to-C-Part-1 (1).docIntroduction-to-C-Part-1 (1).doc
Introduction-to-C-Part-1 (1).doc
 
Introduction-to-C-Part-1.pptx
Introduction-to-C-Part-1.pptxIntroduction-to-C-Part-1.pptx
Introduction-to-C-Part-1.pptx
 
Introduction-to-C-Part-1 JSAHSHAHSJAHSJAHSJHASJ
Introduction-to-C-Part-1 JSAHSHAHSJAHSJAHSJHASJIntroduction-to-C-Part-1 JSAHSHAHSJAHSJAHSJHASJ
Introduction-to-C-Part-1 JSAHSHAHSJAHSJAHSJHASJ
 
C++Basics2022.pptx
C++Basics2022.pptxC++Basics2022.pptx
C++Basics2022.pptx
 
Introduction to cpp language and all the required information relating to it
Introduction to cpp language and all the required information relating to itIntroduction to cpp language and all the required information relating to it
Introduction to cpp language and all the required information relating to it
 
Introduction-to-C-Part-1.pdf
Introduction-to-C-Part-1.pdfIntroduction-to-C-Part-1.pdf
Introduction-to-C-Part-1.pdf
 
C++ helps you to format the I/O operations like determining the number of dig...
C++ helps you to format the I/O operations like determining the number of dig...C++ helps you to format the I/O operations like determining the number of dig...
C++ helps you to format the I/O operations like determining the number of dig...
 
ch01_an overview of computers and programming languages
ch01_an overview of computers and programming languagesch01_an overview of computers and programming languages
ch01_an overview of computers and programming languages
 
Lecture-1&2.pdf Visual Programming C# .net framework
Lecture-1&2.pdf Visual Programming C# .net frameworkLecture-1&2.pdf Visual Programming C# .net framework
Lecture-1&2.pdf Visual Programming C# .net framework
 
C++ was developed by Bjarne Stroustrup, as an extension to the C language. cp...
C++ was developed by Bjarne Stroustrup, as an extension to the C language. cp...C++ was developed by Bjarne Stroustrup, as an extension to the C language. cp...
C++ was developed by Bjarne Stroustrup, as an extension to the C language. cp...
 
Session 1 - c++ intro
Session   1 - c++ introSession   1 - c++ intro
Session 1 - c++ intro
 
C++ In One Day_Nho Vĩnh Share
C++ In One Day_Nho Vĩnh ShareC++ In One Day_Nho Vĩnh Share
C++ In One Day_Nho Vĩnh Share
 
Fundamentals of programming with C++
Fundamentals of programming with C++Fundamentals of programming with C++
Fundamentals of programming with C++
 
Introduction to C Programming
Introduction to C ProgrammingIntroduction to C Programming
Introduction to C Programming
 
Lab 1.pptx
Lab 1.pptxLab 1.pptx
Lab 1.pptx
 
How to work with code blocks
How to work with code blocksHow to work with code blocks
How to work with code blocks
 
CIS 170 Life of the Mind/newtonhelp.com   
CIS 170 Life of the Mind/newtonhelp.com   CIS 170 Life of the Mind/newtonhelp.com   
CIS 170 Life of the Mind/newtonhelp.com   
 
CIS 170 Imagine Your Future/newtonhelp.com   
CIS 170 Imagine Your Future/newtonhelp.com   CIS 170 Imagine Your Future/newtonhelp.com   
CIS 170 Imagine Your Future/newtonhelp.com   
 
C++ language basic
C++ language basicC++ language basic
C++ language basic
 
Basics of C Lecture 2[16097].pptx
Basics of C Lecture 2[16097].pptxBasics of C Lecture 2[16097].pptx
Basics of C Lecture 2[16097].pptx
 

Recently uploaded

Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Principled Technologies
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 

Recently uploaded (20)

Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 

2621008 - C++ 1

  • 2. Slide 2 Compilers The 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.
  • 3. 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 10011110 00001 11110100 00010 10011110 00011 11010100 00100 10111111 00101 00000000 Compiler
  • 4. 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
  • 5. 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
  • 6. 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
  • 7. Slide 7 Example Problem  For example: Sorting a stack of papers, each with a number on it
  • 8. 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
  • 9. 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.
  • 10. 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.
  • 11. Slide 11 PROGRAMMING WITH VISUAL C++ The Editor The 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.
  • 12. Slide 12 PROGRAMMING WITH C++ The Linker The 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.
  • 14. Slide 14 PROGRAMMING WITH C++ Phases of C++ program Typical 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
  • 15. 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.
  • 16. 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.
  • 17. Slide 17 PROGRAMMING WITH C++ Phase 3: Compiling a C++ Program In Phase 3, the compiler translates the C++ program into machine-language code
  • 18. 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.
  • 19. 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.
  • 20. 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.
  • 21. Slide 21 A sample of program in C++:
  • 22. 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.
  • 23. 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,
  • 24. 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.
  • 25. 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 intint 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.
  • 26. Slide 26 Declaration of variables Variable Declarations In 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;
  • 27. 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:
  • 28. 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.
  • 29. 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);
  • 30. 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};
  • 31. 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; }
  • 32. 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;
  • 33. Slide 33 PROGRAMMING WITH VISUAL C++ Variable Types
  • 34. 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 add int number2; // second integer to add int sum; // sum of number1 and number2
  • 35. 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.
  • 36. 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
  • 37. 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; }
  • 38. 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.
  • 39. 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);
  • 40. 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; }
  • 41. 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
  • 42. Slide 42 PROGRAMMING WITH VISUAL C++ An Output Statement • Every C++ statement must end with a semicolon (also known as the statement terminator).
  • 43. 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.
  • 44. Slide 44 PROGRAMMING WITH VISUAL C++ 1 2
  • 45. Slide 45 PROGRAMMING WITH VISUAL C++ Ex: The escape sequence n means newline.
  • 46. 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.
  • 47. Slide 47 PROGRAMMING WITH VISUAL C++ Printing Multiple Lines of Text with a Single Statement
  • 48. Slide 48 Another C++ Program: Adding Integers Another C++ Program: Adding Integers Our 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.
  • 49. 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; }
  • 50. 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"};
  • 51. 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; }
  • 52. 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.
  • 53. 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);
  • 54. 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);
  • 55. 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 variables int 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; }