Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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
{ 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++
Sem 7 Asanga Ratnaweera, Department of 2
Mechanical Engineering
1
ME 515 Mechatronics 11/9/2006
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;
Basic components of a
simple C++ Program
// Program: Display greetings
Preprocessor
/* Author(s): A.B.C. Dissanayake
directives
Date: 1/24/2001*/ Comments
#include <iostream>
2
ME 515 Mechatronics 11/9/2006
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++!”;
3
ME 515 Mechatronics 11/9/2006
Introduction to C++
Programming
// Program : Program02.cpp
// Printing a line with multiple statements.
#include <iostream>
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
return 0; // indicate that program ended successfully
} // end function main
4
ME 515 Mechatronics 11/9/2006
Escape sequences
Escape Description
Sequence
\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 9
Mechanical Engineering
A Simple Program:
Printing a Line of Text
// Program : Program03.cpp
// Printing multiple lines with a single statement
#include <iostream>
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();
return 0; // indicate that program ended successfully
5
ME 515 Mechatronics 11/9/2006
char Characters
short
int Numbers without fractions
long (integers)
float
double Numbers with fractions
(floating-point numbers)
long double
String Non-numbers
6
ME 515 Mechatronics 11/9/2006
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;
Sem 7 Asanga Ratnaweera, Department of 13
Mechanical Engineering
C++ Programming
Variables
{ Variable names (identifier)
{ Series of characters (letters, digits,
underscores)
{ Cannot begin with a digit
{ Case sensitive
{ Should not be a keyword
7
ME 515 Mechatronics 11/9/2006
C++ Programming
Input
{ cin - standard input object (connected to
keyboard)
{ >> stream extraction operator ("get from")
#include <iostream>
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 << "Sum is " << sum << endl; // print sum
getchar();
return 0; // indicate that program ended successfully
}
Sem 7 Asanga Ratnaweera, Department of 16
Mechanical Engineering
8
ME 515 Mechatronics 11/9/2006
#include <iostream>
iostream>
#include <cstdio> >
using namespace std;
// programme to add two user input variables
int 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 stored
cout << "Enter first integer = "; // prompt
cin >> value1; // read an integer
cout << "Sum is " << sum << endl; // print sum
getchar();
return 0; // indicate that program ended successfully
}
Sem 7 Asanga Ratnaweera, Department of 17
Mechanical Engineering
C++ Programming
Arithmetic calculations
{ Multiplication *
{ Division /
9
ME 515 Mechatronics 11/9/2006
#include <iostream>
iostream>
#include <cstdio>>
using namespace std;
cout << “The ratio is " << ratio << endl; // print sum
getchar();
return 0; // indicate that program ended successfully
#include <iostream>
iostream>
#include <cstdio> >
using namespace std;
// programme to add two user input variables
int 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 stored
cout << "Enter first integer = "; // prompt
cin >> value1; // read an integer
cout << “The remainder is " << rem << endl; // print sum
getchar();
return 0; // indicate that program ended successfully
}
Sem 7 Asanga Ratnaweera, Department of 20
Mechanical Engineering
10
ME 515 Mechatronics 11/9/2006
if Selection Structure
Selection structure
{ Choose among alternative courses of action
11
ME 515 Mechatronics 11/9/2006
#include <iostream>
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();
return 0;
Sem 7 Asanga Ratnaweera, Department of 23
} Mechanical Engineering
#include <iostream>
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;
Sem 7 } Asanga Ratnaweera, Department of 24
Mechanical Engineering
12
ME 515 Mechatronics 11/9/2006
do/while Repetition
Structure
Similar to while structure
{ Makes loop continuation test at end, not
beginning
{ Loop body executes at least once
Format action(s)
do
{
statement(s) true
condition
}
false
while ( condition );
13
ME 515 Mechatronics 11/9/2006
do {
cout << counter << " "; // display counter
counter = counter+1; // incremental counter
} while (counter <= 10 ); // end do/while
14
ME 515 Mechatronics 11/9/2006
// 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();
return 0; // indicate program ended successfully
// Program : Program07.cpp
// Class average program with sentinel-controlled repetition.
#include <iostream>
iostream>
#include <cstdio>
>
#include <iomanip> // parameterized stream manipulators
using namespace std;
15
ME 515 Mechatronics 11/9/2006
// 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
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
16
ME 515 Mechatronics 11/9/2006
Program next
// Program : Program08.cpp
// Analysis of examination results.
#include <iostream>
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
17
ME 515 Mechatronics 11/9/2006
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)
Sem 7 Asanga Ratnaweera, Department of 36
Mechanical Engineering
18
ME 515 Mechatronics 11/9/2006
19
ME 515 Mechatronics 11/9/2006
20
ME 515 Mechatronics 11/9/2006
// Program : Program09.cpp
// Preincrementing and postincrementing.
#include <iostream>
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();
return 0; // indicate successful termination
}
Sem 7 Asanga Ratnaweera, Department of 41
Mechanical Engineering
#include <iostream>
iostream>
#include <cstdio> >
using namespace std;
// function main begins program execution
int main()
{
int counter = 1; // initialization
} // end while
getchar();
return 0; // indicate successful termination
21
ME 515 Mechatronics 11/9/2006
22
ME 515 Mechatronics 11/9/2006
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
} // end for
cout << "\nBroke out of loop when x became " << x << endl;
getchar();
return 0;
Sem}7 Asanga Ratnaweera, Department of 45
Mechanical Engineering
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
23
ME 515 Mechatronics 11/9/2006
switch Multiple-Selection
Structure
true
case a case a action(s) break
false
true
case b case b action(s) break
false
.
.
.
true
case z case z action(s) break
false
default action(s)
switch Multiple-Selection
Structure
switch
{ Test variable for multiple values
{ Series of case labels and optional statement (s)case
Thisdefault
executed if variable is
switch ( variable ) equal to value1
{
case value1: This statement (s)
statements executed if variable is
break; // necessary totoexit
equal value2switch
or to
value3
case value2:
case value3:
statements This statement (s)
break; executed if variable is
NOT equal to any of the
default: previous case values
statements
break; above.
Sem 7 } Asanga Ratnaweera, Department of 48
Mechanical Engineering
24
ME 515 Mechatronics 11/9/2006
// 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 entered
cout <<“\n\n\t Backward 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;
Sem 7 } Asanga Ratnaweera, Department of 49
Mechanical Engineering
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;
Sem 7 } Asanga Ratnaweera, Department of 50
Mechanical Engineering
25
ME 515 Mechatronics 11/9/2006
Logical Operators
Used as conditions in loops, if
statements
&& (logical AND)
{ true if both conditions are true
if ( gender == 1 && age >= 65 )
++seniorFemales;
|| (logical OR)
{ true if either of condition is true
if ( semesterAverage >= 90 || finalExam >=
90 )
cout << "Student grade is A" << endl;
Sem 7 Asanga Ratnaweera, Department of 51
Mechanical Engineering
#include <iostream>
iostream>
#include <cstdio> >
using namespace std;
int main()
{
int value1; // variable 1
int value2; // variable 2
cout << "Enter 1 if the signal is high or 0 if low :";
cin >> value1; // read value for input signal
cout << "Enter 1 if the signal is high or 0 if low :";
cin >> value2; // read value for input signal
if (value1 == 1 && value2 == 1 ) // AND operation
cout <<“\nAND output is high"<<endl;
if (value1 == 1 || value2 ==1 ) // OR operation
cout <<“\nOR output is high"<<endl;
if (value1 == 0 || value2 ==0 ) // OR operation
cout <<“\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();
Sem 7 return 0; Asanga Ratnaweera, Department of 52
} Mechanical Engineering
26
ME 515 Mechatronics 11/9/2006
Arrays
Consecutive memory locations all referring to same data
type with common name
C++ representation
{ a[7] ={31, 0,-9,17,3,-6,44 };
Arrays
#include <iostream>
iostream>
#include <cstdio>
>
using namespace std;
27
ME 515 Mechatronics 11/9/2006
Arrays
#include <iostream>
iostream>
#include <cstdio> >
using namespace std;
int main()
{
float input_data[] ={1,2,3,4,5}; // Initialization of an integer array
float 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 values
cout << “The element ”<<i<< “ of the output array \t =”<<
output_data[i]<< endl;
}
getchar();
return 0; // indicate successful termination
Sem 7 Asanga Ratnaweera, Department of 55
} // end function main
Mechanical Engineering
File handling
Keyboard I/P is limited and large files are
normally read/written from disk
C++ 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)
28
ME 515 Mechatronics 11/9/2006
File handling
#include <iostream>
iostream>
#include <cstdio>
>
#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:
Sem 7
the data will be Asanga
written to a file data_out.txt at E:/C_data57/
Ratnaweera, Department of
Mechanical Engineering
File handling
#include <iostream>
iostream>
#include <cstdio>>
#include <fstream>
using namespace std;
int main()
{
int i;
float Data_Array[10];
// initialize the array
for(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.txt file should be in your working directory
Sem 7 Asanga Ratnaweera, Department of 58
Mechanical Engineering
29
ME 515 Mechatronics 11/9/2006
30
ME 515 Mechatronics 11/9/2006
31
ME 515 Mechatronics 11/9/2006
Trigonometric functions
#include <iostream.h>
#include <stdlib.h>
#include <conio.h>
#include <math.h> // header file for maths command
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 sine
cout << “ \n\n\t Sine "<< angle<< “ is ”<<sine<<endl;
getch();
return 0; // indicate that program ended successfully
}
Sem 7 Asanga Ratnaweera, Department of 64
Mechanical Engineering
32
ME 515 Mechatronics 11/9/2006
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
}
Hardware addressing
Command : _outp(address, value) or _inp(address,value)
#include <iostream.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h> // header file for Sleep () command
int 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
}
Sem 7 Asanga Ratnaweera, Department of 66
Mechanical Engineering
33
ME 515 Mechatronics 11/9/2006
{ Ex:
int my_function(int x, float y )
float my_function(float x, float y )
getchar();
return 0; // indicate that program ended successfully
}
Sem 7 Asanga Ratnaweera, Department of 68
Mechanical Engineering
34
ME 515 Mechatronics 11/9/2006
35
ME 515 Mechatronics 11/9/2006
Debugging a program
Break points
{ Place the cursor at the line where a break point is to be
place and press F9
Stepping into a function
{ Press F11
Stepping out of a function
{ Press Shift+F11
Stepping over
{ Press F10
Run to the next cursor position
{ Press Ctrl+F10
36