You are on page 1of 67

INTRODUCTION TO C++ AND ITS LANGUAGE BUILDING BLOCKS

Engineer Jokhio Sultan Salahuddin Kohistani Lecturer, Computer Systems Engineering, MUET Jamshoro
E-mail: salah.jokhio@faculty.muet.edu.pk Facebook: http://www.facebook.com/salahuddinjokhio http://www.twitter.com/engrsalahuddinj

Reference Books

Object Oriented Programming in C++

By Robert Lafore. 4th Edition or latest This book will be used as text book.

For Further Studies, you may buy; C++, How to Program

By Dietel and Dietel. By Herbert Scheldt.

C++, The Complete Reference

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

Programming

Programming is all about making the computer to do your own desired work. Computer is like a husband, will do any thing that is said in well format and language according to appropriate language rules. Programming is the art and science of instructing the computer (in an specific language) to do and carry out the said work according to the programmers desires and intents. Requires lot of interest and hard work. Also requires analytical ability (as we are about to solve problems).
3 Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

Mastering the programming


You must have Brain. You must know tactics, such as how to use your Brain?

Draw rough sketch (or flow or solution) in your mind.

Program on a rough page (graphical using flow chart). Dont directly use interactive, intelligent compilers to write programs. Better to do with editors like notepad. Make Mistakes and try to correct them. Think out of Box. Practice, Practice and Practice.

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

Practice

Common English proverb, Practice Makes the Man perfect. Chinese Proverb, I hear, I forget; I see, I remember; I do, I understand. So, Practice as much as you can to master the programming.

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

Learning Approaches

Top Down.

Start from advance and cover the basics as you move further. Used in west. First build the roof then basic blocks. Vice versa of Top Down Approach. Both approaches parallel.

Bottom Up.

Our Approach.

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

Computer Languages

High level Computer Languages


Syntax and Semantics(Rules of Language) very much similar to daily life English sentences and phrases. Easier to learn and easier to implement (to write code) very difficult and complex logics. C++, Java, PHP, ASP.NET, C#.NET all are high level languages. Require either Compiler or Interpreter (or both) to translate into respective Machine code (so that computer can understand). Mostly used to write Consumer and Enterprise Software Applications.

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

Computer Languages

Medium level Computer Languages


Syntax and Semantics are short hand or stenographic representations of commands and phrases. For MOVE, we have mov keyword, for INSERT, we have ins keyword and so on. Assembly Languages for programming Microprocessors, Microcontrollers all are Medium level languages. Bit harder to difficult. Requires knowledge of hardware. Requires Assembler to translate into respective machine code. Harder to learn. Implementing complex logic may be difficult, but still applicable. Used to write control programs for industry control systems, air control systems and other automation projects.
Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

Computer Languages

Low Level Language

Ones and Zeroes. Extremely hard to understand for humans. Understood by Computers only.

What the hell this string mean?

1 0 1 1 0 1 1
9 Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

Towards C++ Language

Machine Language

BCPL Language

C Language

A Language, an Assembly Language

B Language

C++ Language

10

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

C & C++ Language.

C is structured or Functional programming language.

Working on procedural methodology. Also offers Assembly Language to be embedded inside C code.

C++, in addition to classic C Features, also offers programming capability in Object Oriented Paradigm.

Object Oriented Paradigm offers depiction of real world in programming and is including following key features.

11

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

Object Oriented Programming


Polymorphism

Inheritance

OOP

Abstraction

Encapsulation

12

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

Object Oriented Programming

Abstraction

Ideas about problem solving. Rough Sketches. One thing having poly (many) morphs (shapes).

Polymorphism

Inheritance

Allow child programs to inherit different properties from the parent programs.
Provides means of security, by encapsulating (closing and hiding) the data inside its object with certain attributes. Like capsules encapsulates medication.
Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

Encapsulation

13

Compilation of a C++ Program


A .cpp File This requires an editor in which programs are written mostly in notepad Headers files and namespaces
Since header files are imported into the source code, to assure the compatibility this is done. Its automatic

A single .obj File or multiple

An exe Executable File

Here translation is done from c++ to respective code

Here translated obj files and library files are combined and one exe file is created

Editing

Preprocessing

Compiling

Linking

Executing

14

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

Steps to execute a C++ Program


1.

2.
1.

Editing: Requires an editor program to write the source code and must be saved as one of the extension formats as .cpp, .C. Compilation
Preprocessing: A C Preprocessor actually looks for the imported files and classes and collect them for compiling, it works on seeing the preprocessor directives. Compilation: Program is compiled and Machine language code for the respective platform is generated.

2.

3. 4.

Linking: Compiled Libraries and others are linked. Executing: .exe file is executed then to run the program.
Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

15

Basic C++ Program Structure


Preprocessor Directives Mostly some constants are declared. Namespaces are used to identify different names. This is where the execution starts. These all Program statements are executed.

Using Directive
Start of Main Function Program Statements

End of Main Function

Execution Stops here.

16

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

Basic Program outline


#include <some header file>

using namespace namespace-name


int main( ){
Statement(s) come here. return 0;

17

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

Basic C++ Program

18

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

An Alternative Version
#include <iostream> int main() { std::cout << Every age has a language of its own\n; return 0; }

19

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

#include <iostream> The # sign, indicates the use of any preprocessor directive. In this case include is the preprocessor directive. Preprocessor directives are not part of the program, but they are instructions to the compiler, and preprocessor, a part of compiler program, deals with them. It tells the compiler to include the header files in the program. In older versions of C++, extension for header file (.H) was required.
20 Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

#include <iostream>

This iostream header file actually contains the definition of cout, << operator and other basic input/output operations. Other header files could be found in the include folder of your compiler. Some common header files are math, ctype, dos, io etc.

21

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

using namepace std;

The using is another directive, which is used to import namespaces inside the program. Each using command must end with a semicolon (;). Namespace is the part of program, which identifies different names and items inside c++ program statements. The using directive tells the program that statements inside main will be recognized using the std (standard) namespace. cout is also identified inside std namespace.

22

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

int main( )

main is the perhaps the most essential part of any C++ program, which acts as the entry point for statement execution. The Parenthesis followed by main keyword tell the compiler that its the the function, and main shows that it is the main function. Statement inside main are actually executed. Braces limit the functions boundary. { tells the starting of the function, while } tells the ending of the function.

23

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

cout << Hello;


An statement must end with semicolon ( ; ). cout (console-out) is an standard output object which is sending out to the standard connected output device. Mostly Monitor is the standard output object. The thing enclosed in will appear as it would be inside it. The \n will insert a new line after the output, and will force the cursor to blink on the next line.

24

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

return 0;

0 is going to be returned to operating system by main function, which indicates the ending of program and operating systems frees the memory (RAM) space, which was occupied by the program

25

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

White Spaces and Blanks


White Spaces and Blanks are ignored by the compiler. They are mostly for human readability.
Each Header File must be written on separate line, and space between #include and <iostream> is not necessary. While the space between using and namespace and namespaces name is important. Space between int and main is also necessary. So there should be space between C++ reserved keywords. They also must not be used for some other purpose. The Ending bracket can also be put anywhere after the return 0s semicolon.

#include<iostream> using namespace std; int main(){ cout<<Hello World!; return 0; }

26

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

C++ Keywords

These are part of the C++ Language. They can not be used for any other purpose than their defined operation. In previous program, include, using, namespace, int, main, cout, return, they were all c++ reserved keywords. They even can not be used to define **variables.

**Variables will be studied soon in future classes.

27

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

cout

console out displays different data on the screen. For string (a sequence of characters), enclose it into the double quotes. E.g. cout<<This is a Program; For a single character, single quotes E.g. cout<<A; For any number, without quotes or with quotes works same. e.g. cout<<123; e.g. cout<<123; Without quotes, it also performs the arithmetic operation.

28

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

cout

cout << 12a34; cout << af4; cout<< ; cout<< ; cout<<1+3; cout<<1243; cout<<123+654; cout>>asd; cout>>as23asc;

29

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

Cascading cout with <<

We can display multiple outputs in single cout statement by cascading the << several times. So,

cout<<Hello\n<<123<<234+56; is equal to three cout statements.


cout<<Hello\n; cout<<123; cout<<234+56;

30

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

Comments

They are not executed but are ignored by the compiler. They are just for writing some message for future reference purpose. Two Types:

Single Line Comments & Multi- Line Comments Single Line Comments

31

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

Multi-Line comments

32

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

Escape Sequences
They are some special characters Do not appear on the screen, rather their effect can be seen, sensed and felt.

33

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

Manipulators

They are some keywords, which are used to manipulate (modify/change) the output from its original appearance. endl Manipulator

Inserts a new line, and is used with cout statement.

cout<< Hello<<endl<<Bye;

setw Manipulator

Inserts a some spaces in the output, and is used with cout statement. Also requires header file named iomanip

cout<< Hello<<setw(12)<<Bye;

34

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

// width2.cpp // demonstrates setw manipulator #include <iostream> #include <iomanip> // for setw using namespace std; int main() { long pop1=2425785, pop2=47, pop3=9761; cout << setw(8) << LOCATION << setw(12) << POPULATION << endl << setw(8) << Portcity << setw(12) << pop1 << endl << setw(8) << Hightown << setw(12) << pop2 << endl << setw(8) << Lowville << setw(12) << pop3 << endl; return 0; }
35 Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

Output

36

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

Data Types

Data Have Different Types Numeric

Integers (Whole numbers)

short, int and long float and double

Floating point Numbers

Characters

char

True/False

bool (for boolean true/false values)

37

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

Data Types Summary

Note:You dont need to remember this entire table, what you have to remember, is the exact name of the data-type.

Now you have every reason to smile. Smile please but not to laugh, this is not that much easy.
38 Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

Variables
Place

Holders for Data. Named Memory Location inside RAM. They are allowed to change their values. For declaring variable we must:
Name it declare its type (type of data, which will be held) as well.

39

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

Variable Naming Rules


C++ Keyword can not be assigned. Must begin with a English letter or an underscore (_). Can not begin with a number. Names must be meaningful. Names can not be repeated. Different cases can be used. Name can-not contain spaces, but underscores (_) and Hyphens (-) are allowed.

40

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

variable Declaration & Assignment.

Declaration

data-type name; int number1; name = value; number1 = 50; data-type name = value; int number1 = 50;

Assignment

Declaration+Assignment

50
number1

41

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

Variables

short var0 = 51; int var1 = 5000; long var2 = 100000000L; float var3 = 0.52354F; double var4 = 45.236644478; bool isPrime = true; or bool isPrime = 1; char English1 = A;

The single statement is equivalent to two statements like, int num1 = 35678; its equivalent to: int num1; num1 = 35678; Adopt the way you love to do!
42 Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

Program
// charvars.cpp // demonstrates character variables #include <iostream> //for cout, etc. using namespace std; int main() { char charvar1 = A; //define char variable as character char charvar2 = \t; //define char variable as tab cout << charvar1; //display character cout << charvar2; //display character charvar1 = B; //set char variable to char constant cout << charvar1; //display character cout << \n; //display newline character return 0; }

43

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

Constants

Constants are not allowed to change their values. In ANSI C++, constants are defined with const keyword. While in older version constants were implemented by using #define directive. #define being pre-processor directive must be defined at the top of program, while const keyword can be used anywhere inside the function (main in this case). Constants name must contain all capital letters to distinguish it from conventional variables.

44

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

Constants

Lets suppose we want to define one constant, like PI in the following example. Using #define directive

#define PI 3.1415 const float PI = 3.1415;

Using const keyword

45

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

Operators

Arithmetic

+ (Addition) - (Subtraction) * (Multiplication) / (Division) % (Remainder Operator)

To be covered.

46

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

// circarea.cpp // demonstrates floating point variables #include <iostream> //for cout, etc. using namespace std; int main() { float rad; //variable of type float const float PI = 3.14159F; //type const float cout << Enter radius of circle: ; //prompt cin >> rad; float area = PI * rad * rad; //find area cout << Area is << area << endl; //display answer return 0; }
47 Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

The Remainder Operator (%)


Calculates the remainder // remaind.cpp // demonstrates remainder operator #include <iostream> using namespace std; 3)10(3 int main() -9 { = 1 cout << 6 % 8 << endl // 6 << 7 % 8 << endl // 7 (remainder) << 8 % 8 << endl // 0 << 9 % 8 << endl // 1 << 10 % 8 << endl; // 2 return 0; }

48 Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

Expressions in C++

First parenthesis are solved, they multiplication, division and remainder (%) operator are solved and then finally addition and subtraction is carried out and result is assigned to the L.H.S. So, Assignment (=) Operator has the lowest priority. (ftemp-32) * 5 / 9 //ftemp is pre-defined variable. There should be a single variable name at Left hand side of the equation (unlike conventional Math's equation having multiple variables on both sides) and all other things on the Right hand side. So, x+3 = 2y -5 in Maths. But in C++, x= 2y-5-3 or y = (x+3+5) /2.

49

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

Expressions in C++
R.H.S R.H.S R.H.S

X = Y-2-3;
L.H.S

Y= X+3+2;
L.H.S

X+3 = Y-2
L.H.S

But in C++, we must only keep a variable name on L.H.S and all others (Numbers, variables etc) on the either side (R.H.S).
50 Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

Integer Division Rule


Two Axioms/Principles. If Both the operators are integers, result must also be integer. If one of the operator is floating-point number or both are floating-point numbers, then result must also be a floating point number. So, cout<<9/5; will display 1. To see actual result, either keep one number as Floating point or both as floating point. cout<<9.0/5; cout<<9/5.0; cout<<9.0/5.0;

51

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

Input with cin


Used to input some data inside variable. cin>>variable-name; The variable-name is the name of the variable where the data (which will be inputted by the user) will be stored. So, After cin, unlike cout, there must be any variable name. Which should either be pre-declared or pre-initialized.

52

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

Temperature conversion program


// fahren.cpp // demonstrates cin, newline #include <iostream> using namespace std; int main() { int ftemp; //for temperature in fahrenheit cout << Enter temperature in fahrenheit: ; cin >> ftemp; int ctemp = (ftemp-32) * 5 / 9; cout << Equivalent in Celsius is: << ctemp << \n; return 0; }
53 Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

Arithmetic Assignment Operator


Binary Operators (requires two operands) Some time called as the op-operator. += -= *= /= A+=3; //equivalent to a=a+3 A*=3; //equivalent to a=a*3 A/=3; //equivalent to a=a/3 A-=3; //equivalent to a=a-3
54 Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

Program
// assign.cpp // demonstrates arithmetic assignment operators #include <iostream> using namespace std;

int main(){
int ans = 27; ans += 10; //same as: ans = ans + 10; cout << ans << , ; ans -= 7; //same as: ans = ans - 7;

cout << ans << , ;


ans *= 2; //same as: ans = ans * 2; cout << ans << , ; ans /= 3; //same as: ans = ans / 3; cout << ans << , ; ans %= 3; //same as: ans = ans % 3; cout << ans << endl; return 0; }

55

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

The Unary Arithmetic Operators


Requires single operators Also knows as increment and decrement operators The ++ and operators, may be post-fix (after the operand name) or even may be pre-fix (before the operand name. So, ++x is pre-fix, and x++ is post-fix. x++ is same as x = x+1or x+=1 and ++x is also equal to x = x+1. (Same is true for --)

THEN WHAT IS THE DIFFERENCE???????????

56

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

The Unary Arithmetic Operators


#include <iostream> using namespace std; int main(){ int x = 3; cout << ++x <<endl; //will display 4 cout << x++ <<endl; //will also display 4 cout<< x; // will display 5 }

57

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

Program
// increm.cpp // demonstrates the increment operator #include <iostream> using namespace std; int main(){ int count = 10; cout << count= << count << endl; //displays 10 cout << count= << ++count << endl; //displays 11 (prefix) cout << count= << count << endl; //displays 11 cout << count= << count++ << endl; //displays 11 (postfix) cout << count= << count << endl; //displays 12 return 0; }
58 Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

Library Function

We already have used two functions, main is the function, which is most mandatory. we have also used other function named as setw(value), which was a manipulator. Similarly, C++ offers a large variety of library function, which when called, perform some really useful operation. Like sqrt(double number), inside cmath header file calculates the square root of the argument** double type number and it is depicted in the next slide with program. sqrt accepts type double and also returns double type result.

**argument is the input of the function.


Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

59

Program
// sqrt.cpp // demonstrates sqrt() library function #include <iostream> //for cout, etc. #include <cmath> //for sqrt() using namespace std; int main() { double number, answer; //sqrt() requires type double cout << Enter a number: ; cin >> number; //get the number answer = sqrt(number); //find square root cout << Square root is << answer << endl; //display it return 0; }
60 Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

Casts

Casting Processing is done in order to convert from one data type to the other. Two types of casting.

Implicit casting (Also done Automatically by the compiler). Explicit casting (By the Programmer with brute force).

Conversion can be implicit when converting from lower to higher data types, because lower data types can be accommodated in the larger ones, but vice versa may not be true, some of the digits/precision numbers will be lost in the alternative case (Converting from higher to lower) Higher Data Type?? Lower Data Type?? Next Slide
61 Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

Automatic Conversions or Implicit Casting

Types are roughly designated Higher or Lower in the below order.

Program on the next slide for demonstration.


62 Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

Program
#include <iostream> using namespace std; int main() { int count = 7; float avgWeight = 155.5F; double totalWeight = count * avgWeight; cout << totalWeight= << totalWeight << endl; return 0; }

The Result inside totalWeight variable can still be accommodated in a float variable, but double is used just to depict the automatic conversion.

63

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

Explicit Casting

Using static_cast keyword.

Will be covered in the future lectures.

64

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

Assignment # 02

Solve Exercise Questions from 1 to 10 of Chapter 2, Robert Lafores Object oriented Programming in C++.

65

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

So Now.
Whats Next?

Tired! A tight sleep!

66

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro

End of Session 1

What we have learned in this session? Did you practice? If yes, do you often? how much you were able to digest, and what was exhausted? How is C++? These were basics, next chapter deals with more complexities. Get ready, and boost yourself!

67

Engr. J.S. Salahuddin Kohistani, Lecturer, CSE MUET Jamshoro