Anda di halaman 1dari 75

Programming

Tutorial
using C++ for 2 nd

year computer
science students
This tutorial mainly focus
on Laboratory assignments

Prepared by: Geletaw S. &


Ismael K.
Tutorial Objectives
By the end of this
tutorial SWAT:
 Prepare qualified projects
 solve different problems using the
program
 Be ready for future programming
language courses, industrial
attachment and other projects
Tutorial Contents
 Basic concept on conditional
statement & loops.
 Array and Pointer.
 Object oriented concepts such as class
and template functions.
 File handling system such as sequential
and Random file accessing.
 High lights about C++ graphics
 Conditional statements
1. if statements
2. if-else statements
3. switch-case statements
 Loop statements
1. for loop
2. while loop
3. do-while loop
 Breaking control statements
1. Break statement
2. Continue statement
3. goto statements
Arrays
 Processing with array
 Function and arrays
 Multi dimensional arrays
 Character arrays

Pointer
 Pointer and functions( call by value &
reference ,pointer to function & passing a
function to another)
 Pointer and arrays
 Pointer and strings
 Array of pointer
 Pointer to pointer
Class and Template class
 Accessing a member of a class

 Pointer and class

 Array of class objects

Template and Exception Handling


 Function templates

 Class templates

Exception Handling
 Try

 Catch

 throw
File Operations
 Opening and closing of files
 Stream state member functions
 Reading & writing a character from a
file
 Structure, class and file operations
 Array of class object and file
operations
 Random access file processing
Turbo C++ Graphics
Libraries
 Introduction to graphics using C++
Chapter one
Conditional statements
1. if statements
2. if-else statements
3. switch-case statements
Loop statements
1. for loop
2. while loop
3. do-while loop
Breaking control statements
1. Break statement
2. Continue statement
3. goto statements
Revision about Variables,
 statement
Register Variables: used when the variables is
reading or accessing repeatedly.
Syntax: register char temp;
 Static Variables : The content of the variables
retained through out the program.
Syntax: static int x, y; it is the opposite of
automatic variable
 External Variables : variables declared out side
the main.
Syntax : extern int x, y;
 Automatic Variable : a variable declared inside
a function
If statement
Syntax:
If (expression)
For example:
A=20;
B=40;
{ If ( A>B)
statement
{ 1;
statement cout<<“Largest
2; Value is”<< A<<e
}
}
if-else statement
Syntax: For example // Wrong Syntax
if ( i>j)
If (expression) if ( a>b)
Temp=a;
else
statement 1 Temp=b;
For example // Right syntax
else if ( a>b)
statement 2 Temp=a;
else
Temp=b;
switch statement
Syntax: For example:
Switch( exp){
switch( input)
{
case 1: case Y:
statement
case y:
1; cout<<“ the statement is correct\n
break;
break; case n:
case 2: case N:
cout<<“ the statement is incorrect
statement break;
2; default:
break; cout<<“ the statement is false”<<
}
default:
for loop
Syntax:
for( initial condition; test condition; increment or
decrement)
{
statement_1;
statement_2;
}
For example:
for( int i=0;i<5;i--) {
i=i-1;
cout<<i<<‘\t’;
}
for loop con’t….
 Initial condition may not be
required to be declared for some
cases.
For example :
reading a string from a key board
or a file. For this case use the
following syntax:

for( ; (ch=cin.get()) !=‘\n’)


Program reading a line
from the keyboard using
for loop
//A program that reading a string from keyboard
#include<iostream.h>
#include<conio.h>
void main()
{
char ch;
cout<<“enter a line\n”;
for( ; (ch=cin.get() ) !=‘\n’;) {
cout<<“ The character is : “<< endl;
cout.put(ch);
getche();
}
}
for loop con’t….
 Some time for loop may be enter as
for( ; ;)
The above loop is valid but it will
execute the loop indefinitely b/c
there is no condition to be
checked to terminate this loop
while loop
Syntax :
while( condition) {
statement_1;
statemnet_2;
}
For example:
while( (character = cin.get() )!=EOF)
cout.put(character);
Output
As long as character!=EOF while loop
reads a character from the keyboard
and displays on the screen
while loop con’t…
 while loop may use more than one test
condition using different logical
expression as a single statement
For example:
ch=cin.get ();
While(ch!=‘\n’ && ch!=‘\t’)
{
cout.put(ch);
ch=cin.get();
}
The above function check a line feed and
do-while loop
Syntax:
do {
statement 1;
statement 2;
}
while( expression);
For example:
Sum=0,bit=0;
do {
Sum= Sum + bit;
bit=bit+2;
}
while( bit<=30);
Output is 2,4,6,………….,30
break statement

break statement used in case, while loop
For example:
1. case condition:
statement;
break;
default: statement;
2. while loop
while( i<=0)
{
cout<<“enter the number\n”;
cin>>number;
if ( number>0)
{
cout<<“ Invalid Number\n”;
break;
}
}
continue statement
Used to repeat the same operations
once again even if it checks the error
Syntax :
continue;
continue statement
while( i<=0) example
{
cout<<“enter the number\n”;
cin>>number;
if ( number>0)
{
cout<<“ Invalid Number\n”;
continue;
}
}
Output: when ever the number greater than zero
encountered the computer display a message “
Invalid Number” as an error and it continues the
same loop as long as the given condition
satisfied
goto statement
 Used to alter the program execution sequence by
transferring the control to other part of the program.
For example:
int a, b;
cout<<“Enter a & b \n”;
cin>>a>>b;
if (a>b)
goto output1;
else
goto output2;
output1: cout<<“Largest is “ <<a<<endl;
goto stop;
output2: cout<<“largest is “ <<b<<endl;
goto stop;
stop:
}
Arrays
Processing with array
Function and arrays
Multi dimensional arrays
Character arrays
Pointer
Pointer and functions( call by value &
reference ,pointer to function &
passing a function to another)
Pointer and arrays
Pointer and strings
Array of pointer
Pointer to pointer
Processing with array
 The array index must be integer data type
10 20 30 40 50 elements
A[0] A[1] A[2] A[3] A[4] position
For example the following is invalid
for( int x=0; x<=10.11;++0.1)
A[x]=10;
You can define the array size at the
beginning also
i.e. #define Max_Size 100
for ( int i=0;i<=Max_Size-1; i++)
i=i+1;
Function and Array
 The entire array can be passed onto
a function in c ++
 An array name can be used as an
argument for the function declaration
 No subscript or square brackets are
required to invoke a function using
arrays.
Example of array &
#include<iostream.h>function
#include<conio.h>
#define max 100
void main()
{
int sum( int a[ ], int n); // function declaration
int a[max];
int sum;

sum=sum( a,n);// function calling


}
int sum( int a[ ], int n); // function declaration
{
// Local Variable declaration, if any
// Body of the function
return(value);
}
Multi Dimensional Array
For example
int x[2][2]={1,2,3,4};
Output
x[0][0]=1;
x[0][0]=2;
x[0][0]=3;
x[0][0]=4;
Character Array
 The declaration is using alphanumeric
character
char, static char and so on
 Like an integer and floating point, the
character array can also be initialized.
e.g.: char symbol[3]=“com”;
Out put:
symbol[0]=c,symbol[1]=o;symbol[2]=m
e.g. : char name[8]={‘c’ ,’o’ ,’m’ ,’p’ ,’u
’,’t’ ,’e’ ,’r’}
Pointer and Function
 Complex function easily represent
and accessed through pointer.
 Two types
1. call by value
2. call by reference
Call by Value
 A function with formal argument, control
will be transferred from the main to
calling function and the value of the
actual argument is copied to the function.
 With in the function, the actual value
copied from the calling portion of the
program may be altered or changed.
 When the control is transferred back from
the function to the calling portion of the
program, the altered value not
transferred back.
Example for call by value
#include<iostream.h>
void main()
{
void function(int x, int y);// function declaration
int x,y,z;
x=12,y=50;
function(x,y);// call by value
z=x+y;// 12+50=62
cout<<“ sum=“<< x+y<<endll;
}
void function(int a, int b);
{
int sum;
a=a*a;// New value will not be copied to the main
b=b*b;
cout << “ sum=“<< a + b<<endl;
}
Call by reference
 The address of the data item is passed to
the function
 The content of the variables that are
altered with in the function block are
returned to the calling portion of the
program in the altered form itself, as the
formal & the actual argument are
referencing the same memory location or
address called call by reference/by
address or By location
 Any change that is made to the data item
will be recognized in both the function &
the calling portion of the program.
 The use of the pointer as a function
For example:
// call by reference
#include<iostream.h>
#include<conio.h>
void main()
{
int x , y;
void interchange( int *x, int *y);// fun declaration
x=100,y=200;
cout<<“Value before interchange “<<endl;
cout<<“ x=“<<x<<“ and y=“<<y<<endl;
interchange( &x, &y);// call by reference
cout<<“Value after interchange “<<endl;
cout<<“ x=“<<x<<“ and y=“<<y<<endl;
}
void interchange( int *x, int *y)// Value will be swapped
{
int intermediate; Output
intermediate=*x; before exchange x=100, y=200
*x=*y; and after exchange y=200,x=100
*y=intermediate;
}
Pointer to function
declaration
Syntax: return_type(*variables) ( list
of parameters)
2. A program to find the sum three
numbers using a pointer to function
method.
// pointer to functions
#include<iostream.h>
#include<conio.h>
void main()
{
float average(float,float,float);
float a, b, c, avg;
float (*ptrf) (float, float, float);
// pointer to function declaration
ptrf=&average;
cout<<“ Enter the number a, b,
c”<<endl;
cin>>a>>b>>c;
avg=(*ptrf) (a, b, c);// function calling
using pointer

cout<<“a=“<<a<<“b=“<<b<<“c=“<<
c<<endl;
float average (float x, float y, float z)
{
float temp;
temp=(x+y+z)/3.0;
return(temp);
}
Passing a function to another
Syntax:
function
return_type function_name (pointer_to_function
(other argument));
For example:
float sum (float (*) (float, float), float, float);
Pointer and Multi
dimensional array
Pointer Initialization example
ptr=&value[ 0][ 0][ 1];

For pointer and multi dimensional


array see the following example
#include<iostream.h>
#include< conio.h>
void main()
{
static int a[2][3]={ {11,12,13}, {14,15,16}};
int *ptr;
int i, j, n, m, temp;
n=2;
m=3;
cout<<“content of the array “<<endl;
for (i=0; i<=n-1; ++i)
{
for (j=0; j<m-1;++j)
{
temp=*(* (a + i) +j);
cout<<temp<<‘\t’; Out put
} 11, 12,13
cout<<endl; 14,15,16
Pointer and String
 String is terminated by a null
character or ‘\0’
 String constant are written in double
quotes.
 Pointer mainly used for when
perform string operations such as
string compare, string copy, string
concatenate and so on
Question about Pointer and
String
Suppose string1 contain “computer” and
string2 contain “ science”. Write the
program that:
 Copy the content of the string1 to string
3
 Compare the content of string1 and
string2
 Concatenate string1 and string 2
 Find the length of string1
 Search one character from string1
Copy one sting to
another string
 The command strcpy used to copy
one string to another string.
 Syntax: strcpy( destination, source);
that is copy the source to
destination.
Find the length of string
 The command strlen find the length
of a string.
 Syntax: strlen(computer);
 Out put : length=8
String comparison
 The command strcmp used to
compare two strings
 Syntax: strcmp(string1,string2); if
the two string are the same it
returns zero.

 strcmpi compare the string with out


case sensitivity.
String concatenation
 The command strcat used to append or
concatenate on string to the end of
another string.
 Syntax : strcat( “turbo ”, “c++”);
 Out put: Turbo c++
Scanning a character from
the string
 The command strchr used to search or
scan a character from the string in
forward direction only.
 Syntax: strchr( string, character);
searching or scanning the character from
the string.
Upper and Lower case
conversion
 strupr used to change the string into
upper case letter
 Syntax: strupr (string);
 Strlwr used to change a string to
lower case letter.
 Syntax: strlwr (string);
Pointer to Pointer
 The first pointer contain the address of
the second pointer, which points to the
variable that contain the values desired.

Pointer Variable

Pointer Pointer Variable

Syntax: int **ptr;


Class and Objects

Function oriented programming OOP


2. User defined types-----------------
Classes
3. Variables ---------------------------- Objects

4. Structure members ---------------


Instance variables
5. Functions --------------------------- Methods
6. Function Call ----------------------
Message Passing
Class con’t…
 typedef is not required since a class
name is a type of name.
 Keywords private, protected and public
which specify the three levels of access
protection for hiding data and function
members internal to the class.
Private section
1. A member data can only be
accessed by the member function
and friends of this class.
2. The member functions and friends
of this class can always read and
write private data members.
3. Private data member is not
accessible to the out of the class.
Protected section
 Can only be accessed by the member
functions and friends of this class
and also these function can be
accessed by the member functions
and friends derived from this class.
 It is not accessible out of the class
Public section
 Can be accessed by any section out of
the class
 The public implementation operations are
also called as member functions or
methods, or interfaces to out of the class.
 A class by default all its members private

class
{
int a, b;
}
File Handling System
Input/Output with files
 ofstream: Stream class to write on files
 ifstream: Stream class to read from
files
 fstream: Stream class to both read and
write from/to files.
Basic file operation
// basic file operations
#include <iostream.h>
#include <fstream.h>
int main ()
{
ofstream myfile;// File declaration
myfile.open ("example.txt“); // opening
file
myfile << "Writing this to a file.\n";
myfile.close(); // closing file
return 0;
}
Opening file
 In order to open a file with a stream
object we use its member function
open():
 Syntax : open (filename, mode);
 Filename: is a null-terminated character
sequence of type const char * (the same
type that string literals have)
representing the name of the file to be
opened.
 Mode : is an optional parameter with a
combination of the following flags.
ios :: in Open for input operations
ios ::out Open for output operations
ios :: Open in binary mode : Default is
binary
ios :: app text mode
Set the initial position at the end
of the file.
If this flag is not set to any value,
ios :: the initial position
All output operations areis the
trunc beginning
performed of at the
the file.
end of the file,
appending the content to the
current content of the file. This
flag can only be used in streams
ios :: ate open
If the for
fileoutput-only operations
opened for output
operations already existed
before, its previous content is
File stream flag con’t...

ios :: Open a file if a file does exist


nocreate
ios :: Open a file if a file does not
replace exist
File con’t…
 All these flags can be combined using the
bitwise operator OR (|).
 For example, if we want to open the file
“example. Bin” in binary mode to add
data we could do it by the following call
to member function open():
 Syntax:

ofstream myfile; // declaring a file


myfile.open ("example.bin", ios::out | ios::app
| ios::binary); // opening a file for input,
output and binary mode
Remark:
 For ifstream and ofstream classes,
ios::in and ios::out are automatically and
respectively assumed, even if a mode
that does not include them is passed as
second argument to the open() member
function.
Class default
Parameter
3. ifstream ---------------------- ios :: in
4. ofstream ---------------------- ios :: out
5. fstream ---------------------- ios :: in |ios ::
File notes
 The default value is only applied if the
function is called without specifying any
value for the mode parameter.
 If the function is called with any value in
that parameter the default mode is
overridden, not combined.
 File streams opened in binary mode
perform input and output operations
independently of any format
considerations.
 Non-binary files are known as text files,
and some translations may occur due to
formatting of some special characters
Closing file
 The function close( ) is used to close a file
which has been opened for a file
processing such as read, to write and for
both to read and write.
 The close( ) member function is called
automatically by the destructor functions.
 Syntax: myfile.close();
Checking state flags
 In addition to eof(), which checks
if the end of file has been
reached, other member functions
exist to check the state of a
stream (all of them return a bool
value):
bad()
 Returns true if a reading or writing operation
fails. For example in the case that we try to write
to a file that is not open for writing or if the
device where we try to write has no space left.
 Check whether any invalid file operations has
been attempted.

 Example:
#include<iostream.h>
#include<conio.h>
void main() {
ifstream infile;
ifstream.open( “text”);
if ( infile.bad() ) {
cerr<<“ Open failure “<<endl;
exit(1);
}
}
fail ( )
 Returns true in the same cases as bad(),
but also in the case that a format error
happens, like when an alphabetical
character is extracted when we are
trying to read an integer number.
 To check whether a file has been opened
for input or output successfully, or any
invalid operations are attempted or
there is unrecoverable error.
For example
#include <iostream.h>
#include<conio.h>
void main()
{
ifstream infile;
infile.open (“text”);
while( !infile.fail() )
{
cout<<“couldn’t open file”<<endl;
continue;
}
}
eof()
 Returns true if a file open for reading has
reached the end.
 Used to check whether the file reach the
end of file or not
 For example:

main( )
{
ifstream infile;
infile.open (“text”);
while ( !infile.eof () )
{
}

}
good()
 It is the most generic state flag: it
returns false in the same cases in which
calling any of the previous functions
would return true.
 In order to reset the state flags
checked by any of these member
functions we have just seen we can
use the member function clear(),
which takes no parameters.
Checking state flags
In addition to eof(), which checks if the end of
file has been reached, other member functions
exist to check the state of a stream (all of them
return a bool value):
 bad()
 Returns true if a reading or writing operation fails. For
example in the case that we try to write to a file that is
not open for writing or if the device where we try to
write has no space left.
 fail()
 Returns true in the same cases as bad(), but also in the
case that a format error happens, like when an
alphabetical character is extracted when we are trying
to read an integer number.
 eof()
 Returns true if a file open for reading has reached the
end.
 good()
 It is the most generic state flag: it returns false in the
same cases in which calling any of the previous
functions would return true.

Anda mungkin juga menyukai