Upload
muhammad-usman-ghani
View
68
Download
2
Tags:
Embed Size (px)
DESCRIPTION
Introduction to C++ Programming
Citation preview
Introduction to C++ Programming
Engr. Muniba DCSE UET Peshawar
Contents of Week 02
Data types, Constants
Floating Point Constants, Size, Memory Concepts
Names, Keywords, Identifiers
Declaration and Definition of Variables
A Simple Program: Printing a Line of Text
Another Simple Program: Adding Two Integers
3
Introduction to C++ Programming
C++ language
Facilitates structured and disciplined approach to computer program design
Following several examples
Illustrate many important features of C++
Each analyzed one statement at a time
Structured programming
Object-oriented programming
4
A Simple C++ Example // C++ simple example #include //for C++ Input and Output int main () { int number3; std::cout > number3; int number2, sum; std::cout > number2; sum = number2 + number3; std::cout
5
Important Parts of a C++ program
Comments: //, /* . */
Preprocessor directives : #include
Function main Body of the function
Return statement
Other statements
6
Comments
A comment is descriptive text used to help a reader of the program understand its content.
Explain programs to other programmers Improve program readability
Ignored by compiler Single-line comment
Begin with // Example
//allows program to output data to the screen.
Multi-line comment Start with /* End with */ Also called comment delimiter
7
Preprocessor Directives
Preprocessor directives
Processed by preprocessor before compiling
Begin with #
Example
#include
Tells preprocessor to include the input/output stream header file
White spaces
Blank lines, space characters and tabs
Delimiter, used to make programs easier to read
Extra spaces are ignored by the compiler
8
Function main
A part of every C++ program
Exactly one function in a program must be main
main is a Keyword.
Keyword : A word in code that is reserved by C++ for a specific use.
Header of function main : int main( )
Body is delimited by braces ({ })
9
Statements
Instruct the program to perform an action
All statements end with a semicolon (;)
Examples :
return 0;
std::cout
10
return Statement
Because function main() returns an integer value, there must be a statement that indicates what this value is.
The statement return 0 ; indicates that main() returns a value of zero to the
operating system. The value 0 indicates the program terminated successfully greater than 0 means an error maybe a different number for a different error if declare our function as int and don't use return will get a
warning from the compiler
One of several means to exit a function Used at the end of main
Namespaces
Namespace: a generalization of scope.
C++ allows access to multiple namespaces with the ' :: ' operator
A namespace lets us distinguish between two names from different places
In C++ the standard library is in the std namespace
Things in no namespace are said to be in the Global Namespace
How to use a namespace
std::cout
What about
Very similar to
Also declares cin, cout and endl
In the global namespace not in the std namespace
This is for compatibility with older versions of C++
14
Output Statement (1)
std::cout
15
Output Statement (2)
Escape character : backslash : "\"
Escape sequence : A character preceded by backslash (\)
Indicates special character output
Examples :
"\n" Newline. Cursor moves to beginning of next line on the screen
\t Horizontal tab. Move the screen cursor to the next tab stop.
16
Good Programming Practices
Add comments Every program should begin with a comment that
describes the purpose of the program, author, date and time.
Use good indentation Indent the entire body of each function one level
within the braces that delimit the body of the function. This makes a programs functional structure stand out and helps make the program easier to read.
2003 Prentice Hall, Inc. All rights reserved.
17
1 // Fig. 1.2: fig01_02.cpp
2 // A first program in C++.
3 #include // Preprocessor Directive
4
5 // function main begins program execution
6 int main()
7 {
8 std::cout
18
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.
2003 Prentice Hall, Inc. All rights reserved.
19
1 // Fig. 1.4: fig01_04.cpp
2 // Printing a line with multiple statements.
3 #include
4
5 // function main begins program execution
6 int main()
7 {
8 std::cout
2003 Prentice Hall, Inc. All rights reserved.
20
1 // Fig. 1.5: fig01_05.cpp
2 // Printing multiple lines with a single statement
3 #include
4
5 // function main begins program execution
6 int main()
7 {
8 std::cout
21
Input stream object
std::cin from Usually connected to keyboard Stream extraction operator >>
Waits for user to input value, press Enter (Return) key Stores value in variable to right of operator
Converts value to variable data type
Example int number1; std::cin >> number1;
Reads an integer typed at the keyboard Stores the integer in variable number1
2003 Prentice Hall, Inc. All rights reserved.
22
1 // Fig. 1.6: fig01_06.cpp
2 // Addition program.
3 #include
4
5 // function main begins program execution
6 int main()
7 {
8 int integer1; // first number to be input by user
9 int integer2; // second number to be input by user
10 int sum; // variable in which sum will be stored
11
12 std::cout > integer1; // read an integer
14
15 std::cout > integer2; // read an integer
17
18 sum = integer1 + integer2; // assign result to sum
19
20 std::cout
23
Memory Concepts
Variable names
Correspond to actual locations in computer's memory
Every variable has name, type, size and value
When new value placed into variable, overwrites old value
Writing to memory is destructive
Reading variables from memory nondestructive
Example
sum = number1 + number2;
Value of sum is overwritten
Values of number1 and number2 remain intact
24
Fig.1| Memory location showing the name and value of
variable number1.
25
Fig. 2| Memory locations after storing values for
number1 and number2.
26
Fig. 3 | Memory locations after calculating and storing
the sum of number1 and number2.
age.cpp
#include
using namespace std;
int main()
{
int age=26;
cout
Statements
Instructions
Finish with a ;
(semicolon)
#include
using namespace std;
int main()
{
int age=26;
cout
Statement Block
List of instructions
Everything between { and }
(curly brackets, braces)
#include
using namespace std;
int main()
{
int age=26;
cout
Functions One of the building block of the C++ program.
#include
using namespace std;
int main()
{
int age=26;
cout
Data Types
int, float, void, unsigned int, long, double, char
string, list,
Ways to represent information
#include
using namespace std;
int main()
{
int age=26;
cout
Data Type: Char
Size : Single byte
Range: -128 : 127
Hold one character such as a or A
Variable declaration: char ch;
ch = a; // stores a character value a
Data Type: int
Size: 2 bytes
Range: -32768 : 32767
Holds the integer value specified in the range
Type long or long int
Size: 4 bytes
Range: -2,147,483,648 : 2,147,483,647
Data Type: float
Size: 4 bytes
Range: 10e-38 : 10e38 with 6 digits of precision
Holds the numbers that have fractional part e.g., 12.55
Data Type: double
Size: 8 bytes
Range: 10e308 : 10e-308
Holds floating point numbers with 15 digits of precision
Type: long double
Range: 10e-4932 : 10e4932
void datatype
Special data type to represent nothing or an unknown type of data
int main(void)
main function expects nothing
Exactly the same as int main()
void main()
main function returns nothing
In C++ main() should always return an int
Keywords
Sometimes called reserved words.
Are defined as a part of the C++ language.
Reserved for specific purpose
Have special meaning and is known by compiler
Can not be used for anything else!
Examples:
char, int, float, void, signed, if, while, case, else
class, public, friend, this, operator, new, true
Keywords
#include
using namespace std;
int main()
{
int age=26;
cout
39
Keywords
Cannot be used as identifiers or variable names
C++ Keywords
Keywords common to the C and C++ programming languages
auto break case char const
continue default do double else
enum extern float for goto
if int long register return
short signed sizeof static struct
switch typedef union unsigned void
volatile while
C++ only keywords
asm bool catch class const_cast
delete dynamic_cast explicit false friend
inline mutable namespace new operator
private protected public reinterpret_cast
static_cast template this throw true
try typeid typename using virtual
wchar_t
Constants
Constant is a fixed value that does not change during the execution of the program.
Divided into two types
Numeric Constants
Non-Numeric Constants
Numeric Constants
Numbers are referred to as Numeric Constants Consists of
Numeric digits 0-9 Plus (+) or Minus (-) sign If no sign by-default it is assumed to be positive Decimal point No commas or blanks are allowed
Examples 30 -500 3.14159 0.25432 +100
Numeric Constants
Represented in three ways
Integer constant
Floating-point constant
Exponential real constant
Integer Constant
The numeric constant that doesnt contain a decimal point
Can be positive or negative
Examples 70
+134
0
-500
7
Floating-Point Constants
The numeric constants that does contain the decimal point
Can be either positive or negative
Examples
0.3
-56.34
0.008976
Exponential Real Constants
Floating point constant in the E-notation form. Widely used in scientific & engineering
applications. Used to represent very small or very large
numbers Examples
1.23E+2 1.0E3 8.8E-6 3.33E-2
Non-Numeric Constants
Used for non-numeric purposes
To produce output reports, headings, or printing messages
Divided into two types
Character Constants
String Constants
Character Constants
Singular!
One character defined character set.
Surrounded on the single quotation mark.
All the alphabetic, numeric and special characters can be
character constants except backslash and the single quotation
mark.
Examples:
A
a
$
4
\\ for backslash
\ for single quote
String Constants
A sequence characters surrounded by double
quotation marks.
Considered a single item.
Examples:
UMBC
I like ice cream.
123
CAR
car
Names
Sometimes called identifiers.
Words that are not reserved.
User defined words or the programmer supplied
names
Can be of any length, but on the first 31 are
significant (too long is as bad as too short).
Are case sensitive:
abc is different from ABC
Must begin with a letter and the rest can be
letters, digits, and underscores.
Identifiers
Variable names and object names
age, height, i, j, x, y, cout
Also function names
main
#include
using namespace std;
int main()
{
int age=26;
cout
Variables
Specific storage location in memory where value can be stored
A value, which may vary during program execution.
A variable is the name used to represent a piece of information.
Declaration & Definition of Variables
All the variables must defined and declared before usage.
Declaration introduces a variables name into a program
If the declaration also set aside memory for the variables it is called the definition
Variables can be assigned a value at the time of declaration
Declaration statements
int age;
string user_name;
float height, weight;
int age=26;
string user_name="Matt";
float height=1.75, weight=122.5;
54
Algorithms
Computing problems
Solved by executing a series of actions in a specific order
Algorithm a procedure determining
Actions to be executed
Order to be executed
Example: recipe
Program control
Specifies the order in which statements are executed
55
Pseudocode
Pseudocode
Artificial, informal language used to develop algorithms
Similar to everyday English
Not executed on computers
Used to think out program before coding
Easy to convert into C++ program
Only executable statements
No need to declare variables