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
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
A Simple C++ Example
// C++ simple example
#include <iostream> //for C++ Input and Output int main ()
{
int number3;
std::cout << "Enter a number:"; std::cin >> number3;
int number2, sum;
std::cout << "Enter another number:"; std::cin >> number2;
sum = number2 + number3;
std::cout << "Sum is: " << sum <<std::endl; return 0;
standard output stream object stream insertion operator
stream extraction operator standard input stream object
stream manipulator
5
Important Parts of a C++ program
• Comments:
//, /* …. */• Preprocessor directives :
#include• Function
main– Body of the function – Return statement
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 */
7
Preprocessor Directives
• Preprocessor directives
– Processed by preprocessor before compiling – Begin with #
– Example
• #include <iostream>
– Tells preprocessor to include the input/output stream header file <iostream>
• White spaces
– Blank lines, space characters and tabs
– Delimiter, used to make programs easier to read – Extra spaces are ignored by the compiler
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;
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
How to use a namespace
std::cout << "Hello";
– Specify that this cout object is from the std namespace
using namespace std;
– Copy everything from the std namespace into the global namespace
using std::cout;
– Copy cout from the std namespace into the global namespace
What about <iostream.h>
• Very similar to <iostream>
• Also declares cin, cout and endl
– In the global namespace not in the std namespace
• This is for compatibility with older versions of C++
Output Statement (1)
std::cout << “Welcome to C++!\n”;
– std::cout
• Standard output stream object.
• Defined in input/output stream header file <iostream>
• We are using a name (cout) that belongs to “namespace” std. • Normally outputs to computer screen.
– Stream insertion operator <<
• Value to right (right operand) inserted into left operand.
• The string of characters contained between “ ” after the operator << shows on computer screen.
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”
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 program’s 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 <iostream> // Preprocessor Directive 4
5 // function main begins program execution 6 int main()
7 {
8 std::cout << "Welcome to C++!\n"; 9
10 return 0; // indicate that program ended successfully 11
12 } // end function main
Welcome to C++!
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 <iostream>
4
5 // function main begins program execution 6 int main()
7 {
8 std::cout << "Welcome "; 9 std::cout << "to C++!\n";
10
11 return 0; // indicate that program ended successfully 12
13 } // end function main
Welcome to C++!
A Simple Program: Printing a Line of Text
20
1 // Fig. 1.5: fig01_05.cpp
2 // Printing multiple lines with a single statement
3 #include <iostream> 4
5 // function main begins program execution
6 int main()
7 {
8 std::cout << "Welcome\nto\n\nC++!\n"; 9
10 return 0; // indicate that program ended successfully
11
12 } // end function main
Welcome to
C++!
A Simple Program: Printing a Line of Text
21
Input stream object
• std::cin from <iostream>
– 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
22
1 // Fig. 1.6: fig01_06.cpp
2 // Addition program.
3 #include <iostream>
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 << "Enter first integer\n"; // prompt
13 std::cin >> integer1; // read an integer
14
15 std::cout << "Enter second integer\n"; // prompt
16 std::cin >> integer2; // read an integer
17
18 sum = integer1 + integer2; // assign result to sum
19
20 std::cout << "Sum is " << sum << std::endl; // print sum
21
22 return 0; // indicate that program ended successfully
Enter first integer 45
Enter second integer 72
Sum is 117
Another Simple Program: Adding Two Integers
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
Fig.1| Memory location showing the name and value of variable number1.
25
Fig. 2| Memory locations after storing values for number1 and number2.
Fig. 3 | Memory locations after calculating and storing the sum of number1 and number2.
age.cpp
#include <iostream> using namespace std; int main() { int age=26;cout << "I am " << age << " years old" << endl;
age++; /* add one */
cout << "Next year I will be " << age << endl; return 0;
Statements
• Instructions • Finish with a ‘;’ (semicolon) #include <iostream> using namespace std; int main() { int age=26;cout << "I am " << age << " years old" << endl;
Statement Block
• List of instructions
• Everything between ‘{’ and ‘}’
(curly brackets, braces)
#include <iostream>
using namespace std;
int main()
{
int age=26;
cout << "I am " << age << " years old" << endl; age++; /* add one */
cout << "Next year I will be " << age << endl; return 0;
Functions
• One of the building block of the C++ program.
#include <iostream>
using namespace std;
int main()
{
int age=26;
cout << "I am " << age << " years old" << endl;
age++; /* add one */
Data Types
• int, float, void, unsigned int, long, double, char • string, list, …
• Ways to represent information
#include <iostream>
using namespace std;
int main() {
int age=26;
cout << "I am " << age << " years old" << endl;
age++; /* add one */
cout << "Next year I will be " << age << endl; return 0;
Data Type: Char
• Size : Single byte • Range: -128 : 127
• Hold one character such as ‘a’ or ‘A’ • Variable declaration: char ch;
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
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
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
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 <iostream> using namespace std; int main() { int age=26;cout << "I am " << age << " years old" << endl;
age++; /* add one */
cout << "Next year I will be " << age << endl; return 0;
39
Keywords
• Cannot be used as identifiers or variable names
C++ Keyw o rd s
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
Constants
• Constant is a fixed value that does not change during the execution of the program.
• Divided into two types
– 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 doesn’t 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
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
String Constants
A sequence characters surrounded by double
quotation marks.
Considered a single item. Examples:
“UMBC”
“I like ice cream.” “123”
“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
Identifiers
• Variable names and object names– age, height, i, j, x, y, cout
• Also function names
– main #include <iostream> using namespace std; int main() { int age=26;
cout << "I am " << age << " years old" << endl;
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 variable’s 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";
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
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