ME 515 Mechatronicseng.pdn.ac.lk/old/mechanical/menu/class/downloads/notes/slides.pdf · ME 515...

36
ME 515 Mechatronics 11/9/2006 1 ME 515 Mechatronics Introduction to C++ Asanga Ratnaweera Department of Mechanical Engineering Faculty of Engineering University of Peradeniya Tel: 081239 (3627) Email: [email protected] Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering 2 Introduction to C++ Programming C++ Improves on many of C's features Has object-oriented capabilities Increases software quality and reusability Developed by Bjarne Stroustrup at Bell Labs in 1980 Called "C with classes" C++ (increment operator) - enhanced version of C Superset of C Can use a C++ compiler to compile C programs Gradually evolve the C programs to C++

Transcript of ME 515 Mechatronicseng.pdn.ac.lk/old/mechanical/menu/class/downloads/notes/slides.pdf · ME 515...

Page 1: ME 515 Mechatronicseng.pdn.ac.lk/old/mechanical/menu/class/downloads/notes/slides.pdf · ME 515 Mechatronics 11/9/2006 2 Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

ME 515 Mechatronics 11/9/2006

1

ME 515 Mechatronics

Introduction to C++Asanga Ratnaweera

Department of Mechanical EngineeringFaculty of Engineering

University of PeradeniyaTel: 081239 (3627)

Email: [email protected]

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

2

Introduction to C++ Programming

C++Improves on many of C's featuresHas object-oriented capabilities

Increases software quality and reusabilityDeveloped by Bjarne Stroustrup at Bell Labs in 1980

Called "C with classes"C++ (increment operator) - enhanced version of C

Superset of CCan use a C++ compiler to compile C programsGradually evolve the C programs to C++

Page 2: ME 515 Mechatronicseng.pdn.ac.lk/old/mechanical/menu/class/downloads/notes/slides.pdf · ME 515 Mechatronics 11/9/2006 2 Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

ME 515 Mechatronics 11/9/2006

2

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

3

Introduction to C++ Programming

Output in C++Included in iostream.h header filecout - standard output stream (connected to screen)<< stream insertion operator ("put to")cout << "hi";

Puts "hi" cout, which prints it on the screenEnd line

endl;Stream manipulator - prints a newline and flushes output buffer

Some systems do not display output until "there is enough text to be worthwhile"endl forces text to be displayed

CascadingCan have multiple << or >> operators in a single statementcout << "Hello " << "there" << endl;

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

4

// Program: Display greetings/* Author(s): A.B.C. DissanayakeDate: 1/24/2001*/#include <iostream>

using namespace std;

int main() {cout << "Hello world!" << endl;return 0;

}

Basic components of a simple C++ Program

Preprocessor directives

InsertionstatementEnds executions

of main() which ends program

Comments

Function

Function named main()

indicates start of program

Provides simple access

Page 3: ME 515 Mechatronicseng.pdn.ac.lk/old/mechanical/menu/class/downloads/notes/slides.pdf · ME 515 Mechatronics 11/9/2006 2 Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

ME 515 Mechatronics 11/9/2006

3

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

5

Introduction to C++ Programming

// Program : Program01.cpp// First program in C++.

#include <iostream.h>// function main begins program executionint main()

{cout << "Welcome to C++!”;

return 0; // indicate that program ended successfully} // end function main

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

6

Visual C++ EditorsClick new on file menu to create a new fileSelect file tab on new dialogue box

Select C++ Source FileClick OKWrite the codeSave with the extension cpp

Page 4: ME 515 Mechatronicseng.pdn.ac.lk/old/mechanical/menu/class/downloads/notes/slides.pdf · ME 515 Mechatronics 11/9/2006 2 Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

ME 515 Mechatronics 11/9/2006

4

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

7

Visual C++ EditorsTo compile a program

Press Ctrl+F7To build a program

Press F7This will straight away compile and link a program

To execute a programPress Ctrl+F5

This will straight away compile and link and execute a program

To run a programPress F5

All these commands are available in Build Minibar

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

8

Introduction to C++ Programming

// Program : Program02.cpp// Printing a line with multiple statements.

#include#include <<iostreamiostream>>#include#include <<cstdio>>using namespace std;// function main begins program executionint main(){

cout << "Welcome "; cout << "to C++!\n“<<endl;getchar(); // program waits until key board input is givenreturn 0; // indicate that program ended successfully

} // end function main

Page 5: ME 515 Mechatronicseng.pdn.ac.lk/old/mechanical/menu/class/downloads/notes/slides.pdf · ME 515 Mechatronics 11/9/2006 2 Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

ME 515 Mechatronics 11/9/2006

5

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

9

Escape sequences 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.

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

10

A Simple Program:Printing a Line of Text

// Program : Program03.cpp// Printing multiple lines with a single statement

#include#include <<iostreamiostream>>#include#include <<cstdio>>using namespace std;// function main begins program executionint main()

{cout <<" \t\t Welcome to C++! \n\n“ <<endl; // Tabs and new linecout <<“ My First Programme \a“ <<endl; // Alert soundcout <<“ \t\t\t\t\"Bye\“ "<<endl; // double quotationgetchar();

return 0; // indicate that program ended successfully

} // end function main

Page 6: ME 515 Mechatronicseng.pdn.ac.lk/old/mechanical/menu/class/downloads/notes/slides.pdf · ME 515 Mechatronics 11/9/2006 2 Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

ME 515 Mechatronics 11/9/2006

6

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

11

C++ Data Types

charshortintlong

floatdoublelong double

String

Numbers without fractions(integers)

Numbers with fractions(floating-point numbers)

Non-numbers

Characters

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

12

0 to 1boolean1 bitbool

1.2E +/- 4932 (19 digits)none10long double

1.7E +/- 308 (15 digits)none8double

3.4E +/- 38 (7 digits)none4float

0 to 4,294,967,295unsigned long int4unsigned long

-2,147,483,648 to 2,147,483,647signed long integer4long

0 to 65,535unsigned short integer2unsigned short

-32,768 to 32,767signed short integer2short

0 to 255unsigned character1unsigned char

-128 to 127signed character1char

system dependent* unsigned integersystem dependentunsigned int

system dependent* signed integersystem dependentint

Range of ValuesOther NameBytesType Name

* signed means the number can be positive or negative.

Page 7: ME 515 Mechatronicseng.pdn.ac.lk/old/mechanical/menu/class/downloads/notes/slides.pdf · ME 515 Mechatronics 11/9/2006 2 Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

ME 515 Mechatronics 11/9/2006

7

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

13

C++ ProgrammingVariables

Location in memory where value can be storedCommon data types

int - integer numberschar - charactersdouble - floating point numbers

Declare variables with name and data type before useint integer1;int integer2;int sum;

Can declare several variables of same type in one declaration

Comma-separated listint integer1, integer2, sum;

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

14

C++ ProgrammingVariables

Variable names (identifier)Series of characters (letters, digits, underscores)Cannot begin with a digitCase sensitiveShould not be a keyword

Page 8: ME 515 Mechatronicseng.pdn.ac.lk/old/mechanical/menu/class/downloads/notes/slides.pdf · ME 515 Mechatronics 11/9/2006 2 Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

ME 515 Mechatronics 11/9/2006

8

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

15

C++ ProgrammingInput

cin - standard input object (connected to keyboard)>> stream extraction operator ("get from")cin >> myVariable;

Gets stream from keyboard and puts it into myVariable

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

16

#include#include <<iostreamiostream>>#include#include <<cstdio >>using namespace std;

// programme to add two user input variablesint 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 storedcout << "Enter first integer = "; // promptcin >> integer1; // read an integer

cout << "Enter second integer = "; // promptcin >> integer2; // read an integer

sum = integer1 + integer2; // assign result to sum

cout << "Sum is " << sum << endl; // print sumgetchar();return 0; // indicate that program ended successfully

}

Page 9: ME 515 Mechatronicseng.pdn.ac.lk/old/mechanical/menu/class/downloads/notes/slides.pdf · ME 515 Mechatronics 11/9/2006 2 Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

ME 515 Mechatronics 11/9/2006

9

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

17

#include#include <<iostreamiostream>>#include#include <<cstdio>>using namespace std;

// programme to add two user input variablesint main()

{double value1; // first number to be input by user double value2; // second number to be input by user double sum; // variable in which sum will be storedcout << "Enter first integer = "; // promptcin >> value1; // read an integer

cout << "Enter second integer = "; // promptcin >> value2; // read an integer

sum = value1 + value2; // assign result to sum

cout << "Sum is " << sum << endl; // print sumgetchar();return 0; // indicate that program ended successfully

}

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

18

C++ ProgrammingArithmetic calculations

Multiplication *Division /

Integer division truncates remainder7/5 evaluates to 1

Modulus operator %Modulus operator returns remainder

7%5 evaluates to 2

Page 10: ME 515 Mechatronicseng.pdn.ac.lk/old/mechanical/menu/class/downloads/notes/slides.pdf · ME 515 Mechatronics 11/9/2006 2 Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

ME 515 Mechatronics 11/9/2006

10

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

19

#include#include <<iostreamiostream>>#include#include <<cstdio>>using namespace std;

// programme to add two user input variablesint main()

{double value1; // first number to be input by user double value2; // second number to be input by user double ratio; // variable in which sum will be storedcout << "Enter first integer = "; // promptcin >> value1; // read an integer

cout << "Enter second integer = "; // promptcin >> value2; // read an integer

ratio = value1/value2; // assign result to sum

cout << “The ratio is " << ratio << endl; // print sumgetchar();return 0; // indicate that program ended successfully

}

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

20

#include#include <<iostreamiostream>>#include#include <<cstdio>>using namespace std;

// programme to add two user input variablesint main()

{int value1; // first number to be input by user int value2; // second number to be input by user int rem; // variable in which sum will be storedcout << "Enter first integer = "; // promptcin >> value1; // read an integer

cout << "Enter second integer = "; // promptcin >> value2; // read an integer

rem = value1%value2; // assign result to sum

cout << “The remainder is " << rem << endl; // print sumgetchar();return 0; // indicate that program ended successfully

}

Page 11: ME 515 Mechatronicseng.pdn.ac.lk/old/mechanical/menu/class/downloads/notes/slides.pdf · ME 515 Mechatronics 11/9/2006 2 Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

ME 515 Mechatronics 11/9/2006

11

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

21

Equality and Relational Operators

Standard operator C++ equality Example Meaning

> > x > y x is greater than y

< < x < y x is less than y

≥ >= x >= y x is greater than or equal to y

≤ <= x <= y x is less than or equal to y

= = x = y x is assigned with y

= == x == y x is equal to y

≠ != x != y x is not equal to y

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

22

if Selection StructureSelection structure

Choose among alternative courses of actionIf the condition is true

Print statement executed, program continues to next statement

If the condition is falsePrint statement ignored, program continues

Indenting makes programs easier to readC++ ignores whitespace characters (tabs, spaces, etc.)

Page 12: ME 515 Mechatronicseng.pdn.ac.lk/old/mechanical/menu/class/downloads/notes/slides.pdf · ME 515 Mechatronics 11/9/2006 2 Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

ME 515 Mechatronics 11/9/2006

12

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

23

#include#include <<iostreamiostream>>#include#include <<cstdio>>using namespace std;int main()

{int num; // first number to be read from usercout << "Enter an integer variable : “;cin >> num;

// num % 2 computes the remainder when num is divided by 2if ( num % 2 == 0 ){

cout << num << “ \t is an Even Number" <<endl;cout << “Enter another number" <<endl;

}else{

cout << num << " \t is Odd Number“<< endl;cout << “ Enter another number" <<endl;

}getchar();

return 0;}

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

24

#include#include <<iostreamiostream>>#include#include <<cstdio>>using namespace std;

// simple if statementint main(){

int number; cout<<"Enter an integer number" <<endl;cin>> number; if (number == 1)

cout<<"You entered 1.“<<endl; else if (number > 1)

cout<<"That number is greater than 1.“ <<endl; else if (number < 1)

cout<< "That number is less than 1.“ <<endl; else

cout<<"That wasn't a number.“ <<endl; getchar()

return 0;}

Page 13: ME 515 Mechatronicseng.pdn.ac.lk/old/mechanical/menu/class/downloads/notes/slides.pdf · ME 515 Mechatronics 11/9/2006 2 Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

ME 515 Mechatronics 11/9/2006

13

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

25

while Repetition StructureRepetition structure

Action repeated while some condition remains true

while there are more items on my shopping list Purchase next item and cross it off my list

while loop repeated until condition becomes false

Exampleint product = 2;while ( product <= 1000 )

product = 2 * product;

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

26

do/while Repetition StructureSimilar to while structure

Makes loop continuation test at end, not beginningLoop body executes at least once

Formatdo

{statement(s)

} while ( condition );

true

false

action(s)

condition

Page 14: ME 515 Mechatronicseng.pdn.ac.lk/old/mechanical/menu/class/downloads/notes/slides.pdf · ME 515 Mechatronics 11/9/2006 2 Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

ME 515 Mechatronics 11/9/2006

14

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

27

// Using the do/while repetition structure.#include#include <<iostreamiostream>>#include#include <<cstdio>>using namespace std;

// function main begins program executionint main()

{int counter = 1; // initialize counter (essential)

do { cout << counter << " "; // display counter

counter = counter+1; // incremental counter} while (counter <= 10 ); // end do/while

cout <<“End of program”<< endl;getchar();return 0; // indicate successful termination

} // end function main

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

28

// Program : Program06.cpp// Class average program with counter-controlled repetition.

#include#include <<iostreamiostream>>#include#include <<cstdio>>int main()

{int total; // sum of grades input by userint gradeCounter; // number of grade to be entered nextint grade; // grade valueint average; // average of grades

// initialization phasetotal = 0; // initialize totalgradeCounter = 1; // initialize loop counter

Ex: Average of 10 input values

Page 15: ME 515 Mechatronicseng.pdn.ac.lk/old/mechanical/menu/class/downloads/notes/slides.pdf · ME 515 Mechatronics 11/9/2006 2 Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

ME 515 Mechatronics 11/9/2006

15

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

29

// processing phasewhile ( gradeCounter <= 10 ) { // loop 10 times

cout << "Enter grade: "; // prompt for inputcin >> grade; // read grade from usertotal = total + grade; // add grade to totalgradeCounter = gradeCounter + 1; // increment

counter}

// termination phaseaverage = total / 10; // integer division

// display resultcout << "Class average is " << average << endl;

getchar();return 0; // indicate program ended successfully

} // end function main

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

30

// Program : Program07.cpp

// Class average program with sentinel-controlled repetition.

#include#include <<iostreamiostream>>#include#include <<cstdio>>#include#include <iomanip> // parameterized stream manipulatorsusing namespace std;

// function main begins program execution

int main()

{

int total; // sum of grades

int gradeCounter; // number of grades entered

int grade; // grade value

double average; // number with decimal point for average

// initialization phase

total = 0; // initialize total

gradeCounter = 0; // initialize loop counter

Page 16: ME 515 Mechatronicseng.pdn.ac.lk/old/mechanical/menu/class/downloads/notes/slides.pdf · ME 515 Mechatronics 11/9/2006 2 Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

ME 515 Mechatronics 11/9/2006

16

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

31

// processing phase

// get first grade from user

cout << "Enter grade, -1 to end: "; // prompt for input

cin >> grade; // read grade from user

// loop until sentinel value read from user

while ( grade != -1 ) {

total = total + grade; // add grade to total

gradeCounter = gradeCounter + 1; // increment counter

cout << "Enter grade, -1 to end: "; // prompt for input

cin >> grade; // read next grade

} // end while

// termination phase

// if user entered at least one grade ...

if ( gradeCounter != 0 ) {

// calculate average of all grades entered

average = static_cast< double >( total ) / gradeCounter;

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

32

// display average with one digits of precisioncout << "Class average is " << setprecision( 2 )<< average << endl;

} // end if part of if/else

else // if no grades were entered, output appropriate messagecout << "No grades were entered" << endl;

getchar();return 0; // indicate program ended successfully

} // end function main

Note : 1. static_cast< double > will convert the integer variable to double variable2. setprecision( n ) set the number of decimal places to n-1, where n is an integer

Page 17: ME 515 Mechatronicseng.pdn.ac.lk/old/mechanical/menu/class/downloads/notes/slides.pdf · ME 515 Mechatronics 11/9/2006 2 Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

ME 515 Mechatronics 11/9/2006

17

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

33

Nested Control StructuresRefine

Print a summary of the exam results and decide if tuition should be raised

toPrint the number of passesPrint the number of failuresIf more than eight students passed

Print “Raise tuition”

Program next

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

34

// Program : Program08.cpp// Analysis of examination results.#include#include <<iostreamiostream>>#include#include <<cstdio>>using namespace std;

// function main begins program executionint main(){

// initialize variables in declarationsint passes = 0; // number of passesint failures = 0; // number of failuresint studentCounter = 1; // student counterint result; // one exam result

// process 10 students using counter-controlled loopwhile ( studentCounter <= 10 )

{// prompt user for input and obtain value from user

cout << "Enter result (1 = pass, 2 = fail): ";cin >> result;

Page 18: ME 515 Mechatronicseng.pdn.ac.lk/old/mechanical/menu/class/downloads/notes/slides.pdf · ME 515 Mechatronics 11/9/2006 2 Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

ME 515 Mechatronics 11/9/2006

18

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

35

// if result 1, increment passes; if/else nested in whileif ( result == 1 ) // if/else nested in while

passes = passes + 1;

else // if result not 1, increment failures failures = failures + 1; // increment studentCounter so loop eventually terminates

studentCounter = studentCounter + 1; } // end while

// termination phase; display number of passes and failurescout << "Passed " << passes << endl; cout << "Failed " << failures << endl;

// if more than eight students passed, print "raise tuition"if ( passes > 8 )

cout << "Raise tuition " << endl; getchar();return 0; // successful termination

} // end function main

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

36

Assignment OperatorsAssignment expression abbreviations

Addition assignment operatorc = c + 3; abbreviated to c += 3;

Statements of the formvariable = variable operator expression;

can be rewritten asvariable operator= expression;

Other assignment operators

d -= 4 (d = d - 4)e *= 5 (e = e * 5)f /= 3 (f = f / 3)g %= 9 (g = g % 9)

Page 19: ME 515 Mechatronicseng.pdn.ac.lk/old/mechanical/menu/class/downloads/notes/slides.pdf · ME 515 Mechatronics 11/9/2006 2 Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

ME 515 Mechatronics 11/9/2006

19

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

37

Increment and Decrement OperatorsIncrement operator (++)

Increment variable by onec++

Same as c += 1 (C=C+1)

Decrement operator (--) similar Decrement variable by onec--

Same as c -= 1 (C=C-1)

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

38

Increment and Decrement OperatorsPre-increment

Variable changed before used in expressionOperator before variable (++c or --c)

Post-incrementIncremented changed after expression

Operator after variable (c++, c--)

Page 20: ME 515 Mechatronicseng.pdn.ac.lk/old/mechanical/menu/class/downloads/notes/slides.pdf · ME 515 Mechatronics 11/9/2006 2 Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

ME 515 Mechatronics 11/9/2006

20

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

39

Increment and Decrement OperatorsIf c = 5, then

cout << ++c;c is changed to 6, then printed out

cout << c++;Prints out 5 (cout is executed before the increment.) c then becomes 6

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

40

Increment and Decrement OperatorsWhen variable not in expression

Pre-incrementing and post-incrementing have same effect

++c;cout << c;

and c++; cout << c;

are the same

Page 21: ME 515 Mechatronicseng.pdn.ac.lk/old/mechanical/menu/class/downloads/notes/slides.pdf · ME 515 Mechatronics 11/9/2006 2 Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

ME 515 Mechatronics 11/9/2006

21

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

41

// Program : Program09.cpp// Preincrementing and postincrementing.

#include#include <<iostreamiostream>>#include#include <<cstdio>>using namespace std;

// function main begins program executionint main()

{int c; // declare variable// demonstrate postincrementc = 5; // assign 5 to ccout <<“C is ”<<c << endl; // print 5cout <<“C++ is ”<< c++ << endl; // print 5 then post-incrementcout <<“New C is”<< c << endl ; // print 6

// demonstrate preincrementc = 5; // assign 5 to ccout <<“C is ”<<c << endl; // print 5cout <<“++C is ”<< ++c << endl; // pre-increment and print 6cout <<“New C is”<< c << endl ; // print 6

getchar();return 0; // indicate successful termination

}

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

42

#include#include <<iostreamiostream>>#include#include <<cstdio>>using namespace std;// function main begins program execution

int main(){

int counter = 1; // initialization

while ( counter <= 10 ) // repetition condition{

cout << counter << endl; // display counter++counter; // increment

} // end while getchar();

return 0; // indicate successful termination

} // end function main

Page 22: ME 515 Mechatronicseng.pdn.ac.lk/old/mechanical/menu/class/downloads/notes/slides.pdf · ME 515 Mechatronics 11/9/2006 2 Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

ME 515 Mechatronics 11/9/2006

22

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

43

for Repetition StructureGeneral format when using for loopsfor ( initialization; LoopContinuationTest;

increment )statement

Exampleint counter;

for( counter = 1; counter <= 10; counter++ )cout << counter << endl;

Prints integers from one to tenNo semicolon after last statement

Where the counter variable is ONLY used within the for block, the variable can be declared within the for structure. For example, these two statements can be replaced by:

for ( int counter = 1; counter <= 10; counter++ )

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

44

for Repetition Structure

#include#include <<iostreamiostream>>#include#include <<cstdlibcstdlib>>using namespace std;

// function main begins program executionint main(){

// Initialization, repetition condition and incrementing // are all included in the for structure header. for ( int counter = 1; counter <= 10; counter++ )

cout << “counter” << endl; getchar();

return 0; // indicate successful termination} // end function main

Page 23: ME 515 Mechatronicseng.pdn.ac.lk/old/mechanical/menu/class/downloads/notes/slides.pdf · ME 515 Mechatronics 11/9/2006 2 Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

ME 515 Mechatronics 11/9/2006

23

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

45

int main(){int x; // x declared here so it can be used after the loop

// loop 10 timesfor ( x = 1; x <= 10; x++ )

{// if x is 5, terminate loop

if ( x == 5 )break; // break loop only if x is 5

cout << x << " "; // display value of x

} // end for cout << "\nBroke out of loop when x became " << x << endl;

getchar();return 0;}

Break Command

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

46

int main(){

// loop 10 timesfor ( int x = 1; x <= 10; x++ ){// if x is 5, continue with next iteration of loop

if ( x == 5 )continue; // skip remaining code in loop body

cout << x << " "; // display value of x

} // end for structurereturn 0; // indicate successful termination}

Continue Command

Page 24: ME 515 Mechatronicseng.pdn.ac.lk/old/mechanical/menu/class/downloads/notes/slides.pdf · ME 515 Mechatronics 11/9/2006 2 Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

ME 515 Mechatronics 11/9/2006

24

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

47

switch Multiple-Selection Structure

true

false

.

.

.

case a case a action(s) break

case b case b action(s) break

false

false

case z case z action(s) break

true

true

default action(s)

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

48

switch Multiple-Selection Structureswitch

Test variable for multiple valuesSeries of case labels and optional default case

switch ( variable ) {

case value1: statementsbreak; // necessary to exit switch

case value2:case value3:

statementsbreak;

default: statementsbreak;

}

This statement (s) executed if variable is equal to value1

This statement (s) executed if variable is equal to value2 or to value3

This statement (s) executed if variable is NOT equal to any of the previous case values above.

Page 25: ME 515 Mechatronicseng.pdn.ac.lk/old/mechanical/menu/class/downloads/notes/slides.pdf · ME 515 Mechatronics 11/9/2006 2 Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

ME 515 Mechatronics 11/9/2006

25

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

49

// Program : Program14.cp// please add the required header files// function main begins program execution

int main(){char value; cout << "Enter + for Clockwise motion or - for Anticlockwise motion: "; cin >> value; // read value from use

switch ( value){ case '+': // + is entered

cout<<“\n\n\t Forward motion is executed\n\n"<<endl;break;

case '-': // - is enteredcout <<“\n\n\t Backward motion is executed\n\n"<<endl;break;

default: // catch all other characterscout << "Incorrect entry.“ << " Enter a new direction." << endl;break; // optional; will exit switch anyway

}getchar();return 0;}

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

50

int main(){int value; cout << "Enter 1 for Clockwise motion or 2 for Anticlockwise motion: "; cin >> value; // read value from use

switch ( value){ case 1: { // 1 is entered

cout<<“Forward motion is executed"<<endl;cout<<“The motor is rotating in clockwise direction"<<endl;}break;

case 2: { // 2is enteredcout<<"Backward motion is executed"<<endl;cout<<“The motor is rotating in anticlockwise direction"<<endl;}break;default: // catch all other characterscout << "Incorrect entry.“ << " Enter a new direction." << endl;break; // optional; will exit switch anyway

}getchar();return 0;}

Page 26: ME 515 Mechatronicseng.pdn.ac.lk/old/mechanical/menu/class/downloads/notes/slides.pdf · ME 515 Mechatronics 11/9/2006 2 Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

ME 515 Mechatronics 11/9/2006

26

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

51

Logical OperatorsUsed as conditions in loops, if statements&& (logical AND)

true if both conditions are trueif ( gender == 1 && age >= 65 )

++seniorFemales;

|| (logical OR)true if either of condition is trueif ( semesterAverage >= 90 || finalExam >= 90 )

cout << "Student grade is A" << endl;

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

52

#include#include <<iostreamiostream>>#include#include <<cstdio>>using namespace std;int main(){

int value1; // variable 1int value2; // variable 2

cout << "Enter 1 if the signal is high or 0 if low :";cin >> value1; // read value for input signalcout << "Enter 1 if the signal is high or 0 if low :";cin >> value2; // read value for input signal

if (value1 == 1 && value2 == 1 ) // AND operationcout <<“\nAND output is high"<<endl;

if (value1 == 1 || value2 ==1 ) // OR operationcout <<“\nOR output is high"<<endl;

if (value1 == 0 || value2 ==0 ) // OR operationcout <<“\nAND output is low"<<endl;

if (value1 == 0 && value2 ==0 )cout <<" \nOR output is low"<<endl;

if (value1 > 1 && value2 > 1 )cout<<“\nWrong Signal"<<endl;

getchar();return 0;

}

Page 27: ME 515 Mechatronicseng.pdn.ac.lk/old/mechanical/menu/class/downloads/notes/slides.pdf · ME 515 Mechatronics 11/9/2006 2 Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

ME 515 Mechatronics 11/9/2006

27

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

53

Arrays Consecutive memory locations all referring to same data type with common name

a[0] a[1] a[2] a[3] a[4] a[5] a[6] locations31 0 -9 17 3 -6 44 values

Size of a[7] declare as int a[7] (single dimension)

C++ representationa[7] ={31, 0,-9,17,3,-6,44 };

Multidimensional arrays (ex: two dimensional)A[3][5]

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

54

Arrays#include#include <<iostreamiostream>>#include#include <<cstdio>>using namespace std;

// function main begins program executionint main(){int input_data[] ={1,2,3,4,5}; // Initialization of an integer array

// displaying valuescout << “The 1st element of the array \t =”<< input_data[0]<< endl;

cout << “The last element of the array\t=”<< input_data[4]<< endl;getchar();

return 0; // indicate successful termination} // end function main

Page 28: ME 515 Mechatronicseng.pdn.ac.lk/old/mechanical/menu/class/downloads/notes/slides.pdf · ME 515 Mechatronics 11/9/2006 2 Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

ME 515 Mechatronics 11/9/2006

28

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

55

Arrays#include#include <<iostreamiostream>>#include#include <<cstdio>>using namespace std;int main(){

float input_data[] ={1,2,3,4,5}; // Initialization of an integer arrayfloat output_data[10];

// Conversion of miles to kilometers// Multiply each element by 8 and divide by 5 for(int i=0; i<=4;i++){output_data[i]= input_data[i]*8/5 ;

// display the output valuescout << “The element ”<<i<< “ of the output array \t =”<<

output_data[i]<< endl;}

getchar();return 0; // indicate successful termination

} // end function main

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

56

File handling

Keyboard I/P is limited and large files are normally read/written from diskC++ data files are just streams of bytes For keyboard / screen we have used,

#include <iostream> - (cin & cout)

For disc we use,#include <fstream> and define our data by either ifstream(i/p) or ofstream (o/p)

Page 29: ME 515 Mechatronicseng.pdn.ac.lk/old/mechanical/menu/class/downloads/notes/slides.pdf · ME 515 Mechatronics 11/9/2006 2 Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

ME 515 Mechatronics 11/9/2006

29

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

57

File handling#include#include <<iostreamiostream>>#include#include <<cstdio>>#include#include <fstream>using namespace std;

int main(){int i;float Data_Array[10]={1,2,3,4,5,6,7,8,9,10};//writing data to a file data_out.txt

ofstream file_out("E:/C_data/data_out.txt", ios::out);for (i=0; i<10; i++)

file_out <<Data_Array[i]<<endl;cout<<"Data writing is completed"<<endl;

getchar();return 0;}

Note: the data will be written to a file data_out.txt at E:/E:/C_data//

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

58

File handling#include#include <<iostreamiostream>>#include#include <<cstdio>>#include <fstream>using namespace std;

int main(){int i;float Data_Array[10];// initialize the arrayfor(i=0; i<10; i++)

Data_Array[i]=0;/*Read values from the input file data.txt */ifstream Data_in(“E:/C_data/data_out.txt", ios::in);

for(i=0; i<10; i++ )Data_in>>Data_Array[i];

for(i=0; i<10; i++ )cout << Data_Array[i]<<endl;

getch();return 0;}Note: data.txtdata.txt file should be in your working directoryfile should be in your working directory

Page 30: ME 515 Mechatronicseng.pdn.ac.lk/old/mechanical/menu/class/downloads/notes/slides.pdf · ME 515 Mechatronics 11/9/2006 2 Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

ME 515 Mechatronics 11/9/2006

30

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

59

In-built Maths Functions

rounds down to a whole numbercout<<floor(11.5);

(prints 11)

double floor(double x);floor(x)

rounds up to a whole number cout<<ceil(11.2);

(prints 12)

double ceil(double x);ceil(x)

returns the absolute value of a floating point number

double fabs(double x);fabs(x)returns the absolute value of an integer.int abs(int x);abs(x)

PurposePrototypeFunction

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

60

In-built Maths Functions

calculates x to the power of y. If x is negative, y must be an integer. If x is zero, y must be a positive integer.

double pow(double x,double y);

pow(x,y)

calculates the positive square root of x.(x is >=0)

double sqrt(double x);sqrt(x)

returns floating point remainder of x/ywith same sign as x. Y cannot be zero. Because the modulus operator(%) works only with integers, this function is used to find the remainder of floating point number division.

double fmod(double x,double y);

fmod(x,y)

PurposePrototypeFunction

Page 31: ME 515 Mechatronicseng.pdn.ac.lk/old/mechanical/menu/class/downloads/notes/slides.pdf · ME 515 Mechatronics 11/9/2006 2 Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

ME 515 Mechatronics 11/9/2006

31

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

61

In-built Maths Functions#include <iostream.h>#include <stdlib.h>#include <conio.h>#include <math.h> // header file for maths commandint main(){

int integer;float value;float abs_value;float round_up;cout << "Enter an integer "; cin >> integer;cout <<"The absolute value \t= "<<abs(integer) <<endl; //absolute value of integercout <<"\nPress any key to continue "<<endl; getch(); //programme pausescout << "\nEnter a floating point number "; cin >> value;

abs_value = fabs(value); //absolute value of floating point variablecout <<"The absolute value \t= "<<abs_value<<endl;

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

62

cout <<"\nPress any key to continue "<<endl;getch();round_up = ceil(abs_value); //rounding up

cout <<"Round up value \t= "<<round_up<<endl;cout <<"\nPress any key to continue "<<endl; getch();cout <<"Round down value \t= "<<floor(abs_value) <<endl; //rounding downcout <<"\nPress any key to continue "<<endl;getch();cout <<round_up<<" to power "<<abs(integer) <<" is

"<<pow(round_up,abs(integer))<<endl; // variable round_up to power absolute value of variable integer

cout <<"\nPress any key to continue "<<endl;getch();cout <<" Square root of 100 is "<<sqrt(100) <<endl; //square root of 100cout <<"\nPress any key to continue "<<endl;getch();cout <<"The remainder of 4.343/2.342 is "<<fmod(4.343, 2.342) <<endl;//remainder of the floating point divisiongetch();

return 0; // indicate that program ended successfully}

Page 32: ME 515 Mechatronicseng.pdn.ac.lk/old/mechanical/menu/class/downloads/notes/slides.pdf · ME 515 Mechatronics 11/9/2006 2 Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

ME 515 Mechatronics 11/9/2006

32

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

63

In-built Maths Functions

arc tangent xatan(x)

arc sine of xasin(x)

arc cosine xacos(x)

tangent of xtan(x)

sine of xsin(x)

cosine of xcos(x)

base 10 logarithmlog10(x)

natural logarithmlog(x)

exponential functionexp(x)

hyperbolic tangent of xtanh(x)

hyperbolic sine of xsinh(x)

hyperbolic cosine of xcosh(x)

The trigonometric functions work with angles in radians rather than degrees.All of the trigonometric functions take double arguments and have double return types.

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

64

Trigonometric functions #include <iostream.h>#include <stdlib.h>#include <conio.h>#include <math.h> // header file for maths command

# define PI 3.14159265358 // definition of a universal constant

int main(){

float angle;float sine;cout << “ Enter the angle in degrees : "; cin >>angle; sine = sin(angle*PI/180); // converts the degrees to radians and calculates sinecout << “ \n\n\t Sine "<< angle<< “ is ”<<sine<<endl;getch();return 0; // indicate that program ended successfully

}

Page 33: ME 515 Mechatronicseng.pdn.ac.lk/old/mechanical/menu/class/downloads/notes/slides.pdf · ME 515 Mechatronics 11/9/2006 2 Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

ME 515 Mechatronics 11/9/2006

33

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

65

Time delay #include <iostream.h>#include <stdlib.h>#include <conio.h>#include <windows.h> // header file for Sleep () command

int main(){

int count=1;while ( count <= 10) // loop 10 times{

cout << "counter value = "<<count<<endl; count = count + 1;

Sleep(10); // Delay time in ms is given inside the bracket}

getch();return 0; // indicate that program ended successfully

}

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

66

Hardware addressing

#include <iostream.h>#include <stdlib.h>#include <conio.h>#include <windows.h> // header file for Sleep () commandint main(){

_outp(0x378,1); // writes 1 to address 0x378 (parallel port)

sleep(10); // Delay time in ms is given inside the bracket_outp(0x378,0); // writes 0 to address 0x378 (parallel port)

getch();return 0; // indicate that program ended successfully

}

Command : _outp(address, value) or _inp(address,value)

Page 34: ME 515 Mechatronicseng.pdn.ac.lk/old/mechanical/menu/class/downloads/notes/slides.pdf · ME 515 Mechatronics 11/9/2006 2 Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

ME 515 Mechatronics 11/9/2006

34

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

67

User defined functions

Syntaxtype Funtion_name (type variable, type variable, …)

Ex: int my_function(int x, float y )

float my_function(float x, float y )

Return data type Data inputs

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

68

User defined functions #include <iostream.h>#include <stdlib.h>#include <conio.h>#include <windows.h> // header file for Sleep () commandint delayed_counter (int);int main(){

int delay_time;int last;cout<<“Enter the delay time in seconds \t:”;cin>> delay_time;last =delayed_counter (delay_time*1000); // function callcout<<“ Last function value \t:”<<last<<endl;

getchar();return 0; // indicate that program ended successfully

}

Page 35: ME 515 Mechatronicseng.pdn.ac.lk/old/mechanical/menu/class/downloads/notes/slides.pdf · ME 515 Mechatronics 11/9/2006 2 Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

ME 515 Mechatronics 11/9/2006

35

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

69

User defined functions int delayed_counter (int a){int count=1;

while ( count <= 10) { // loop 10 timescout << "counter value = "<<count<<endl; // prompt for input

count = count + 1; // add grade to totalSleep(a); // Delay time in ms

}

return count;}

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

70

User defined functions #include <iostream.h>#include <stdlib.h>#include <conio.h>

float add (float,float);int main(){

float x,y;float addition;cout<<“Enter the first variable \t:”;cin>> x;cout<<“Enter the second variable \t:”;

cin>> y;addition=add (x,y); // calling the function cout<<“The addition is \t:”<<addition<<endl;getch();return 0; // indicate that program ended successfully

}

Page 36: ME 515 Mechatronicseng.pdn.ac.lk/old/mechanical/menu/class/downloads/notes/slides.pdf · ME 515 Mechatronics 11/9/2006 2 Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

ME 515 Mechatronics 11/9/2006

36

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

71

User defined functions

float add (float a, float b)

{

float sum;

sum =a+b;

cout<<“the sum is \t =“ <<sum<<endl;

return sum; // the function returns the value sum

}

Sem 7 Asanga Ratnaweera, Department of Mechanical Engineering

72

Debugging a program

Break pointsPlace the cursor at the line where a break point is to be place and press F9

Stepping into a functionPress F11

Stepping out of a functionPress Shift+F11

Stepping overPress F10

Run to the next cursor positionPress Ctrl+F10