You are on page 1of 55

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

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

A Simple C++ Example


// C++ simple example C++ style comments #include <iostream> //for C++ Input and Output int main () { standard output stream object int number3; stream insertion operator std::cout << "Enter a number:"; std::cin >> number3; int number2, sum; stream extraction operator standard input stream object

std::cout << "Enter another number:"; std::cin >> number2; sum = number2 + number3; std::cout << "Sum is: " << sum <<std::endl; } return 0; stream manipulator Concatenating insertion operators
4

Important Parts of a C++ program


Comments: //, /* . */ Preprocessor directives : #include Function main
Body of the function Return statement Other statements

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

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
7

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 ({ })

Statements
Instruct the program to perform an action All statements end with a semicolon (;) Examples :
return 0; std::cout << Welcome to C++!\n ;

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


10

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 << "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.

14

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.

15

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.
16

17

A Simple Program
1

2 3 4 5 6 7 8 9 10 11 12

// Fig. 1.2: fig01_02.cpp // A first program in C++. #include <iostream> // Preprocessor Directive // function main begins program execution int main() { std::cout << "Welcome to C++!\n"; return 0; // indicate that program ended successfully

} // end function main

Welcome to C++!

2003 Prentice Hall, Inc.


All rights reserved.

A Simple Program: Printing a Line of Text


Escape Sequence \n \t \r Description Newline. Position the screen cursor to the beginning of the next line. Horizontal tab. Move the screen cursor to the next tab stop. Carriage return. Position the screen cursor to the beginning of the current line; do not advance to the next line. Alert. Sound the system bell. Backslash. Used to print a backslash character. Double quote. Used to print a double quote character.

\a \\ \"

18

A Simple Program: Printing a Line of Text


1

19

2 3 4 5 6 7 8 9 10 11 12 13

// Fig. 1.4: fig01_04.cpp // Printing a line with multiple statements. #include <iostream> // function main begins program execution int main() { std::cout << "Welcome "; std::cout << "to C++!\n"; return 0; // indicate that program ended successfully

} // end function main

Welcome to C++!

2003 Prentice Hall, Inc.


All rights reserved.

A Simple Program: Printing a Line of Text


1 2 3 4 5 6 7 8 9 10 11 12 // Fig. 1.5: fig01_05.cpp // Printing multiple lines with a single statement #include <iostream> // function main begins program execution int main() { std::cout << "Welcome\nto\n\nC++!\n"; return 0; // indicate that program ended successfully

20

} // end function main

Welcome to C++! 2003 Prentice Hall, Inc.


All rights reserved.

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

21

Another Simple Program: Adding Two Integers


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 // Fig. 1.6: fig01_06.cpp // Addition program. #include <iostream> // function main begins program execution int main() { int integer1; // first number to be input by user int integer2; // second number to be input by user int sum; // variable in which sum will be stored std::cout << "Enter first integer\n"; std::cin >> integer1; // prompt // read an integer

22

Enter first integer 45 Enter second integer 72 Sum is 117

std::cout << "Enter second integer\n"; // prompt std::cin >> integer2; // read an integer sum = integer1 + integer2; // assign result to sum

std::cout << "Sum is " << sum << std::endl; // print sum return 0; // indicate that program ended successfully

} // end function main

2003 Prentice Hall, Inc.


All rights reserved.

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

23

Fig.1| Memory location showing the name and value of


variable number1.

24

Fig. 2| Memory locations after storing values for number1 and number2.

25

Fig. 3 | Memory locations after calculating and storing the sum of number1 and number2.

26

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; age++; /* add one */ cout << "Next year I will be " << age << endl; return 0; }

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 */ cout << "Next year I will be " << age << endl; return 0; }

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; 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 <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; }

Keywords
Cannot be used as identifiers or variable names
C++ Keyw o rd s
Keywords common to the C and C++ programming languages auto continue enum if short switch volatile C++ only keywords asm delete inline private static_cast try wchar_t break default extern int signed typedef while bool dynamic_cast mutable protected template typeid case do float long sizeof union char double for register static unsigned const else goto return struct void

catch explicit namespace public this typename

class false new reinterpret_cast throw using

const_cast friend operator true virtual

39

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 30 -500 3.14159 0.25432 +100

Examples

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: \\ for backslash A \ for single quote a $

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 <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; }

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;

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
54

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
55

You might also like