1 / 72

ME 515 Mechatronics

ME 515 Mechatronics. Introduction to C++ Asanga Ratnaweera Department of Mechanical Engineering Faculty of Engineering University of Peradeniya Tel: 081239 (3627) Email: asangar@pdn.ac.lk. Introduction to C++ Programming. C++ Improves on many of C's features

carolinec
Download Presentation

ME 515 Mechatronics

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. ME 515 Mechatronics Introduction to C++ Asanga Ratnaweera Department of Mechanical Engineering Faculty of Engineering University of Peradeniya Tel: 081239 (3627) Email: asangar@pdn.ac.lk

  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++ Asanga Ratnaweera, Department of Mechanical Engineering

  3. Introduction to C++ Programming • Output in C++ • Included in iostream.h header file • cout - standard output stream (connected to screen) • << stream insertion operator ("put to") • cout << "hi"; • Puts "hi"cout, which prints it on the screen • End 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 • Cascading • Can have multiple << or >> operators in a single statement cout << "Hello " << "there" << endl; Asanga Ratnaweera, Department of Mechanical Engineering

  4. Preprocessor directives Comments Provides simple access Function named main() indicates start of program Insertion statement Function Ends executions of main() which ends program Basic components of a simple C++ Program // Program: Display greetings /* Author(s): A.B.C. Dissanayake Date: 1/24/2001*/ #include <iostream> using namespace std; int main() { cout << "Hello world!" << endl; return 0; } 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 execution int main() { cout << "Welcome to C++!”; return0; // indicate that program ended successfully } // end function main Asanga Ratnaweera, Department of Mechanical Engineering

  6. Visual C++ Editors • Click new on file menu to create a new file • Select file tab on new dialogue box • Select C++ Source File • Click OK • Write the code • Save with the extension cpp Asanga Ratnaweera, Department of Mechanical Engineering

  7. Visual C++ Editors • To compile a program • Press Ctrl+F7 • To build a program • Press F7 • This will straight away compile and link a program • To execute a program • Press Ctrl+F5 • This will straight away compile and link and execute a program • To run a program • Press F5 • All these commands are available in Build Minibar Asanga Ratnaweera, Department of Mechanical Engineering

  8. Introduction to C++ Programming // Program : Program02.cpp // Printing a line with multiple statements. #include <iostream> #include <cstdio> using namespace std; // function main begins program execution int main() { cout << "Welcome "; cout << "to C++!\n“<<endl; getchar(); // program waits until key board input is given return0; // indicate that program ended successfully } // end function main Asanga Ratnaweera, Department of Mechanical Engineering

  9. Escape sequences 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 <iostream> #include <cstdio> using namespace std; // function main begins program execution int main() { cout <<" \t\t Welcome to C++! \n\n“ <<endl; // Tabs and new line cout <<“ My First Programme \a“ <<endl; // Alert sound cout <<“ \t\t\t\t\"Bye\“ "<<endl; // double quotation getchar(); return0; // indicate that program ended successfully } // end function main Asanga Ratnaweera, Department of Mechanical Engineering

  11. C++ Data Types char short int long float double long double String Characters Numbers without fractions (integers) Numbers with fractions (floating-point numbers) Non-numbers Asanga Ratnaweera, Department of Mechanical Engineering

  12. * signed means the number can be positive or negative. Asanga Ratnaweera, Department of Mechanical Engineering

  13. C++ Programming • Variables • Location in memory where value can be stored • Common data types • int- integer numbers • char - characters • double- floating point numbers • Declare variables with name and data type before use int integer1; int integer2; int sum; • Can declare several variables of same type in one declaration • Comma-separated list int integer1, integer2, sum; Asanga Ratnaweera, Department of Mechanical Engineering

  14. C++ Programming • Variables • Variable names (identifier) • Series of characters (letters, digits, underscores) • Cannot begin with a digit • Case sensitive • Should not be a keyword Asanga Ratnaweera, Department of Mechanical Engineering

  15. C++ Programming • Input • cin- standard input object (connected to keyboard) • >> stream extraction operator ("get from") • cin >> myVariable; • Gets stream from keyboard and puts it into myVariable Asanga Ratnaweera, Department of Mechanical Engineering

  16. #include <iostream> #include <cstdio > using namespace std; // programme to add two user input variables 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 cout << "Enter first integer = "; // prompt cin >> integer1; // read an integer cout << "Enter second integer = "; // prompt cin >> integer2; // read an integer sum = integer1 + integer2; // assign result to sum cout << "Sum is " << sum << endl; // print sum getchar(); return0; // indicate that program ended successfully } Asanga Ratnaweera, Department of Mechanical Engineering

  17. #include <iostream> #include <cstdio> using namespace std; // programme to add two user input variables int main() { double value1; // first number to be input by user doublevalue2; // second number to be input by user double sum; // variable in which sum will be stored cout << "Enter first integer = "; // prompt cin >> value1; // read an integer cout << "Enter second integer = "; // prompt cin >> value2; // read an integer sum = value1 + value2; // assign result to sum cout << "Sum is " << sum << endl; // print sum getchar(); return0; // indicate that program ended successfully } Asanga Ratnaweera, Department of Mechanical Engineering

  18. C++ Programming • Arithmetic calculations • Multiplication * • Division/ • Integer division truncates remainder • 7/5 evaluates to 1 • Modulus operator % • Modulus operator returns remainder • 7%5evaluates to 2 Asanga Ratnaweera, Department of Mechanical Engineering

  19. #include <iostream> #include <cstdio> using namespace std; // programme to add two user input variables int main() { double value1; // first number to be input by user doublevalue2; // second number to be input by user double ratio; // variable in which sum will be stored cout << "Enter first integer = "; // prompt cin >> value1; // read an integer cout << "Enter second integer = "; // prompt cin >> value2; // read an integer ratio = value1/value2; // assign result to sum cout << “The ratio is " << ratio << endl; // print sum getchar(); return0; // indicate that program ended successfully } Asanga Ratnaweera, Department of Mechanical Engineering

  20. #include <iostream> #include <cstdio> using namespace std; // programme to add two user input variables int main() { int value1; // first number to be input by user intvalue2; // second number to be input by user int rem; // variable in which sum will be stored cout << "Enter first integer = "; // prompt cin >> value1; // read an integer cout << "Enter second integer = "; // prompt cin >> value2; // read an integer rem = value1%value2; // assign result to sum cout << “The remainder is " << rem << endl; // print sum getchar(); return0; // indicate that program ended successfully } Asanga Ratnaweera, Department of Mechanical Engineering

  21. Equality and Relational Operators Asanga Ratnaweera, Department of Mechanical Engineering

  22. if Selection Structure • Selection structure • Choose among alternative courses of action • If the condition is true • Print statement executed, program continues to next statement • If the condition is false • Print statement ignored, program continues • Indenting makes programs easier to read • C++ ignores whitespace characters (tabs, spaces, etc.) Asanga Ratnaweera, Department of Mechanical Engineering

  23. #include <iostream> #include <cstdio> using namespace std; int main() { int num; // first number to be read from user cout << "Enter an integer variable : “; cin >> num; // num % 2 computes the remainder when num is divided by 2 if ( 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(); return0; } Asanga Ratnaweera, Department of Mechanical Engineering

  24. #include <iostream> #include <cstdio> using namespace std; // simple if statement int 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; } Asanga Ratnaweera, Department of Mechanical Engineering

  25. while Repetition Structure • Repetition 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 • Example int product = 2; while ( product <= 1000 ) product = 2 * product; Asanga Ratnaweera, Department of Mechanical Engineering

  26. true false action(s) condition do/while Repetition Structure • Similar to while structure • Makes loop continuation test at end, not beginning • Loop body executes at least once • Format do { statement(s) } while ( condition ); Asanga Ratnaweera, Department of Mechanical Engineering

  27. // Using the do/while repetition structure. #include <iostream> #include <cstdio> using namespace std; // function main begins program execution int 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(); return0; // indicate successful termination } // end function main Asanga Ratnaweera, Department of Mechanical Engineering

  28. Ex: Average of 10 input values // Program : Program06.cpp // Class average program with counter-controlled repetition. #include <iostream> #include <cstdio> int main() { int total; // sum of grades input by user int gradeCounter; // number of grade to be entered next int grade; // grade value int average; // average of grades // initialization phase total = 0; // initialize total gradeCounter = 1; // initialize loop counter Asanga Ratnaweera, Department of Mechanical Engineering

  29. // processing phase while ( gradeCounter <= 10 ) { // loop 10 times cout << "Enter grade: "; // prompt for input cin >> grade; // read grade from user total = total + grade; // add grade to total gradeCounter = gradeCounter + 1; // increment counter } // termination phase average = total / 10; // integer division // display result cout << "Class average is " << average << endl; getchar(); return0; // indicate program ended successfully } // end function main Asanga Ratnaweera, Department of Mechanical Engineering

  30. // Program : Program07.cpp // Class average program with sentinel-controlled repetition. #include <iostream> #include <cstdio> #include <iomanip>// parameterized stream manipulators using 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 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; Asanga Ratnaweera, Department of Mechanical Engineering

  32. // display average with one digits of precision cout << "Class average is " << setprecision( 2 )<< average << endl; } // end if part of if/else else// if no grades were entered, output appropriate message cout << "No grades were entered" << endl; getchar(); return0; // indicate program ended successfully } // end function main Note : 1. static_cast< double > will convert the integer variable to double variable 2. setprecision( n ) set the number of decimal places to n-1, where n is an integer Asanga Ratnaweera, Department of Mechanical Engineering

  33. Nested Control Structures • Refine Print a summary of the exam results and decide if tuition should be raised to Print the number of passes Print the number of failures If more than eight students passed Print “Raise tuition” • Program next Asanga Ratnaweera, Department of Mechanical Engineering

  34. // Program : Program08.cpp // Analysis of examination results. #include <iostream> #include <cstdio> using namespace std; // function main begins program execution int main() { // initialize variables in declarations int passes = 0; // number of passes int failures = 0; // number of failures int studentCounter = 1; // student counter int result; // one exam result // process 10 students using counter-controlled loop while ( studentCounter <= 10 ) { // prompt user for input and obtain value from user cout << "Enter result (1 = pass, 2 = fail): "; cin >> result; Asanga Ratnaweera, Department of Mechanical Engineering

  35. // if result 1, increment passes; if/else nested in while if ( 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 failures cout << "Passed " << passes << endl; cout << "Failed " << failures << endl; // if more than eight students passed, print "raise tuition" if ( passes > 8 ) cout << "Raise tuition " << endl; getchar(); return0; // successful termination } // end function main Asanga Ratnaweera, Department of Mechanical Engineering

  36. Assignment Operators • Assignment expression abbreviations • Addition assignment operator c = c + 3; abbreviated to c += 3; • Statements of the form variable = variable operator expression; can be rewritten as variable 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) Asanga Ratnaweera, Department of Mechanical Engineering

  37. Increment and Decrement Operators • Increment operator (++) • Increment variable by one • c++ • Same as c += 1 (C=C+1) • Decrement operator (--) similar • Decrement variable by one • c-- • Same as c -= 1 (C=C-1) Asanga Ratnaweera, Department of Mechanical Engineering

  38. Increment and Decrement Operators • Pre-increment • Variable changed before used in expression • Operator before variable (++c or --c) • Post-increment • Incremented changed after expression • Operator after variable (c++, c--) Asanga Ratnaweera, Department of Mechanical Engineering

  39. Increment and Decrement Operators • If 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 Asanga Ratnaweera, Department of Mechanical Engineering

  40. Increment and Decrement Operators • When variable not in expression • Pre-incrementing and post-incrementing have same effect ++c; cout << c; and c++; cout << c; are the same Asanga Ratnaweera, Department of Mechanical Engineering

  41. // Program : Program09.cpp // Preincrementing and postincrementing. #include <iostream> #include <cstdio> using namespace std; // function main begins program execution int main() { int c; // declare variable // demonstrate postincrement c = 5; // assign 5 to c cout <<“C is ”<<c << endl; // print 5 cout <<“C++ is ”<< c++ << endl; // print 5 then post-increment cout <<“New C is”<< c << endl ; // print 6 // demonstrate preincrement c = 5; // assign 5 to c cout <<“C is ”<<c << endl; // print 5 cout <<“++C is ”<< ++c << endl; // pre-increment and print 6 cout <<“New C is”<< c << endl ; // print 6 getchar(); return0; // indicate successful termination } Asanga Ratnaweera, Department of Mechanical Engineering

  42. #include <iostream> #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(); return0; // indicate successful termination } // end function main Asanga Ratnaweera, Department of Mechanical Engineering

  43. 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++ ) for Repetition Structure • General format when using for loops for ( initialization; LoopContinuationTest; increment ) statement • Example int counter; for( counter = 1; counter <= 10; counter++ ) cout << counter << endl; • Prints integers from one to ten No semicolon after last statement Asanga Ratnaweera, Department of Mechanical Engineering

  44. for Repetition Structure #include <iostream> #include <cstdlib> using namespace std; // function main begins program execution int 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(); return0; // indicate successful termination } // end function main Asanga Ratnaweera, Department of Mechanical Engineering

  45. Break Command int main() { int x; // x declared here so it can be used after the loop // loop 10 times for ( 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; } Asanga Ratnaweera, Department of Mechanical Engineering

  46. Continue Command int main() { // loop 10 times for ( 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 structure return0; // indicate successful termination } Asanga Ratnaweera, Department of Mechanical Engineering

  47. true false true false . . . true false case a action(s) case z action(s) case b action(s) break break break default action(s) case b case a case z switch Multiple-Selection Structure Asanga Ratnaweera, Department of Mechanical Engineering

  48. 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. switch Multiple-Selection Structure • switch • Test variable for multiple values • Series of case labels and optional default case switch ( variable ) { case value1: statements break; // necessary to exit switch case value2: case value3: statements break; default: statements break; } 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\tForward motion is executed\n\n"<<endl; break; case '-': // - is entered cout <<“\n\n\tBackward motion is executed\n\n"<<endl; break; default: // catch all other characters cout << "Incorrect entry.“ << " Enter a new direction." << endl; break; // optional; will exit switch anyway } getchar(); return 0; } 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 entered cout<<"Backward motion is executed"<<endl; cout<<“The motor is rotating in anticlockwise direction"<<endl; } break; default: // catch all other characters cout << "Incorrect entry.“ << " Enter a new direction." << endl; break; // optional; will exit switch anyway } getchar(); return 0; } Asanga Ratnaweera, Department of Mechanical Engineering

More Related