Universiti Malaysia Perlis

oatmealbrothersSoftware and s/w Development

Nov 18, 2013 (3 years and 1 month ago)

52 views






Universiti Malaysia Perlis







DKT216: OBJECT ORIENTED PROGRAMMING

Lab 1: Introduction to C++

















Pusat Pengajian Kejuruteraan Komputer Dan Perhubungan

Universiti Malaysia Perlis




WRITING AND COMPILING A C++ PROGRAM WITH GCC


STEPS

TO VIEW NAVIGATION PANEL

1.

Click Home icon > Window > Show Navigation Panel


STEPS TO CREATE NEW FOLDER


1.

Click Home icon > Edit > Create New > Folder

2.

Rename the New Folder as your name.


STEPS TO START EDITORS


Click Start icon > More Applications > Edi
tors > gedit


STEPS TO CREATE NEW PROGRAM IN gedit





Once you started gedit editors, automatically it will view an Untitled program.


1.

Start typing a program.


// Program example 1

// This program is to display a message of "Welcome To UniMAP"

#include <
stdio.h>

int main( )

{


printf("Welcome To UniMAP");


return 0;

}


2.

Once finished, save the source.


STEPS TO SAVE THE SOURCE FILE


Please follow the instructions below


1.

Go to
File

menu, select
Save as

option

2.

If you want to save in the
current directory

(e.g. /home/yourname), type
welcome.c
in the box besides the text
Location.

OR


if you want to save in
a folder

in the current directory

(e.g. /home/yourname/foldername), click the folder icon and then type
welcome.c
in
the box besides the text
Location
.

Notes :

The filename must be in one word. eg. Program.c or pgm_1.c







STEPS TO COMPILE A PROGRAM



1.

Click Start icon > System > Terminals > Konsole

2.

If you save your program in:

a) the current directory, type
gcc
welcome.c

OR

b) a

folder in the current directory, type
cd

foldername
, then
gcc

welcome.c

3.

Reminder

You can compile and specify the output file name together with the compile command.

gcc
-
o

result welcome.c



OR

gcc
welcome.c

-
o
result



STEPS TO RUN A PROGRAM


1.

Stay in the Konsole window

2.

From Command Prompt, if you

a) did
not

specify the output file name, type
./a.out

OR

b) specify the output file name, type
./result
















// comments.cpp

// demonstrates comments


// A first program in C++

#
include <iostream.h>


// function main begins program execution

int main() {


cout << "I am studying in UniMAP
\
n";


return 0;

// indicate that program ended successfully


}
// end function main



This section is the first part of the introduction to C++. Here we focus on C from which C++
was adopted. C++ extends the C programming language with strong typing, some features
and
-

most importantly

-

object
-
oriented concepts.




Developed in the late 19
70s, C gained an huge success due to the development of UNIX
which was almost entirely written in this language. In contrast to other high level languages, C
was written by programmers for programmers. Thus it allows sometimes, say, weird things
which in o
ther languages such as Pascal are forbidden due to its bad influence on
programming style. Anyway, when used with some discipline, C is as good a language as any
other.



1.0 Comments




A line comments start with a double slash (//) and terminated at the end of the line. An old
style comment or block comment available in C++ is the same as in C. E.g : /* Comment */


















I am studying in UniMAP


2.0

Data Types


Table 7.1:



Built
-
in types.






Variables must be defined prior to their use. These definitions must occur before any
statement, thus they form the topmost part within a
statement block
.


3
.0 Statements




C defines all usual flow control statements. Statements are terminated by a semicolon ``;''.
We can group multiple statements into blocks by enclosing them in curly brackets.

Enter first integer :

12

Enter second integer :

34

Sum is : 46









4
.0 Repetition structures


4
.1 For


// add.cpp

// addition program


#include <iostream.h>


int main () {



int

x, y, sum;
// variables declaration



cout << "Enter first integer :
\
n";

//prompt



cin >> x;


// read an integer x same as scanf() function



cout << "Enter second integer :
\
n";
//prompt



cin >> y;

// read an integer y



sum = x + y;

// sum x and y



cout << "Sum is : " << sum <<endl;
// print sum




return 0;
//indicate that program ended successfully

}

// using the for repetition structure


#include <iostream.h>


int main() {



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



{




cout << counter << "
\
t
";


}



cout << endl;



return 0;


}



4.2
While




4.3 Do…while





1 2 3 4 5 6 7 8 9 10

// Using the while repetition structure


#include <iostream.h>


int main()


{


int counter = 1;



//initialization



while(counter <= 10 )
//repetition condition


{




cout << counter << "
\
t
";


++counter;
//increment


}


return 0;

}

1 2 3 4 5

6 7 8 9 10

// Using the do..while repetition structure


#include <iostream.h>


int main()


{


int counter = 10;

//initialization



do {




cout << counter <<" ";


counter
--
;



//decrement


}
while(counter >=
-
10);

//repetition condition



return 0;

}

10 9 8 7 6 5 4 3 2 1 0
-
1
-
2
-
3
-
4
-
5
-
6
-
7
-
8
-
9
-
10

5
.0 Increment and Decrement Operators



The increment operators
++

and
--

can be explained by the following example. If you have the
following statement sequence


a = a + 1;


b = a;



you can use the preincrement operator


b = ++a;



Similarly, if you have the following order of statements:


b = a;


a = a + 1;



you ca
n use the postincrement operator


b = a++;



Thus, the preincrement operator first increments its associated variable

and then returns the
new value, whereas the postincrement operator first returns the value and then increments its
variable. The same rules apply to the pre
-

and postdecrement operator
--
.





// preincrementing and postincrementing


#include <iostream.h>


int main() {


int c;



c = 5;


cout << c << endl;


// print 5


cout << c++ << endl;
// print 5 then postincrement(++)


cout << c++ << endl

<<endl
;




c = 5;


cout << c << endl;



// print 5


cout << ++c <<endl;
// preincrement then print 6


cout << ++c <<endl;




return 0;



}

5

5

6


5

6

7

//operators, and equility operators.


#include <iostream.h>


int main()

{


int num1;


int num2;



cout <<"Enter 2 integers and I will tell you
\
n"




<<"the relationships they satisfy: ";



cin >>

num1 >> num2;



if(num1 == num2)



cout << num1 << " is equal to " << num2 << endl;



if(num1 != num2)



cout << num1 << " is not equal to " << num2 << endl;



if(num1 < num2)



cout << num1 << " is less than " << num2 << endl;



if(num1 > num2)



cout <<

num1 << " is greater than " << num2 << endl;



if(num1 <= num2)



cout << num1 << " is less than or equal to "



<< num2 << endl;



if(num1 >= num2)



cout << num1 << " is greater than or equal to "




<< num2 << endl;



return 0;

}

6.0 Selection structure

6.1 If statement



The conditional operator
?:

is an abbreviation for a commonly used
if

statement. For
example to assign
max

the maximum of
a

and
b

we can use the following
if

statement:


if (a > b)


max = a;


else


max = b;




When the if statement have an else it
can be expressed as
follows:



max = a > b ? a : b;













































//Counting letter grades


#include <iostream.h>


int main()

{


int choice;


int number1;


int number2;


int number3;



cout << "Enter number 1 "; cin >> number1;



cout << "Enter number 2 "; cin >> number2;



cout << "###########
\
n"




<< "1. Add
\
n"




<< "2. Multiply
\
n"




<< "3. Subtract
\
n"



<< "4. End
\
n"




<< "###########
\
n" ;


do{


cout << "
\
n
\
nE
nter choice :" <<endl;


cin >> choice;




switch (choice) {




case 1:


number3 = number1 + number2;


cout <<"The addition of " << number1 << " & " << number2 <<


" is " << number3;


break;




case 2:


number3 = number1 * number2;


cout <<"The multiplication of " << number1 << " & " <<


number2 << " is " << number3;


break;


















6.2 Switch multiple
-
selection structure











































Enter 2 integers and I will tell you

the relationships they satisfy: 3 7

3 is not equal to 7

3 is less than 7

3 is less than or equal to 7

Enter 2 integers and I will tell you

the relationships they satisfy: 22 12

22

is not equal to 12

22 is greater than 12

22 is greater than or equal to 12



case 3:


number3 = number1/number2;


cout <<"The subtraction of " << number1 << " & " <<


number2

<< " is " << number3;


break;







case 4:



b
reak;



default:



cout << "Incorrect choice entered."


<< "Enter a new choice." <<endl;


break;


}



}while(choice != 4);


return 0;


}





















































Enter number 1 24

Enter number 2 56

###########

1. Add

2. Multiply

3. Subtract

4. End

###########



Enter choice :

1

The addition of 24 & 56 is 80


Enter choice :

2

The multiplication of 24 & 56 is 1344


Enter choice :

3

The subtraction of 24 & 56 is 0


Enter choice :

4

Press any key to continue

1 4 9 16 25 36 49 64 81 100

7.0 Functions



As C is a procedural language it allows the definition of
functions
. Functions are declared
similar to variables, but they enclose their arguments in paren
thesis (even if there are no
arguments, the parenthesis must be specified).





8.0 Array




Arrays are data structure which hold multiple variables of the same data type. In C++,
indexing starts at zero.




To declare an array of 10 integers: int num[10];





To declare an array of 10 character: char word[11];




Character will be terminated by a null character, so we must have an extra space for the null
character.












// creating and using a programmer
-
defined function



#include <iostream.h>



int square( int);

//fuction declaration with one argument



//Function definition



int square(int x)
// local variable


{



return x * x;


}



void main()


{


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





cout<<square(x)<<" ";



cout << endl;






}




Please input numbers :

12

34

56

78

98

12

45

55

33

99



Elements Value


0 12


1 34


2 56


3 78


4 98


5 12


6 45


7 55


8 33


9 99
















































// Initializing an array


#include
<iostream.h>

#include <iomanip.h>


int main()

{


int i, n[10];
// declare i and array of 10 [n]



cout << "Please enter 10 value
\
n";



for (i = 0; i < 10; i++)
// loop 10 times



cin >> n[i];
// input the value of i into array n




cout

<< endl << endl;
// add 2 blank lines




cout << "Elements" << setw(13) << "Value" << endl;




for(i = 0; i < 10; i++)
// loop 10 times again to



cout << setw(7) << i << setw(13) << n[i] << endl;
















return 0;

}

Static = 0

Static = 1

Static = 2

Static = 3

9.0 Pointers




Pointers are variables that contain memory address as their values. Referencing a value
through a pointer is called indirection. The address operator, & returns the address of its
operand.























10.0 Static variable




Static local variables in function retain their value when the function is exited. The next time
the function is called, the static local variable contain the last value it had when the function
exited.


























The

address of a is 0x0012FF7C

The value of aPtr is 0x0012FF7C


The value of a is 7

The value of aPtr is 7

//demoStatic.cpp

#include <iostream.h>

void showV
alue() {



static int svar = 0;



cout << "Static = " <<svar <<endl;



++svar;

}


void main() {


int i = 0;


while(i < 4) {



showValue();



i++;


}

}

//demoPointer.cpp

#include<iostream.h>


int main()


{



int a;



int *aPtr;



a=7;



aPtr = &a;



cout <<"The address of a is " <<&a <<endl





<<"The value of aPtr is " <<aPtr <<endl <<endl;



cout <<"The value of a is " <<a <<endl




<<"The value of aPtr is "<< *aPtr <<endl;



return 0;


}

Exercise


1
. The Fibonacci sequence
a(1), a(2), a(3), ..., a(n), ...

is defined by



a(1) =1




a(2) = 1




a(n) = a(n
-
1) + a(n
-
2)
, for all
n > 2



This generates the sequence

1, 1, 2, 3, 5, 8, 13, 21, ...


Write a C++
function "
fibonacci(...)
" that computes the Fibonacci number corresponding to its
positive integer argument, so that, for example,
fibonacci(7)== 13
.

2
. Given positive two integers m and n such that m<n, the greatest common divisor of m and n
is the
same as the greatest common divisor of m and (n
-
m). Use this fact to write a recursive
definition of the function "
greatest_common_divisor(...)
", which takes two positive integer
arguments and returns their greatest common divisor. Test your function in a
suitable main
program.

3
. Write an Integer function TriangleType(int a,b,c) that accepts as that accepts as


parameters the three sides of a triangle a,b and c and returns


1 if the triangle is scalene


2 if the

triangle is isosceles


3 if the triangle is equilateral


0 if the sides do not forma triangle


HINT: incorporate the Boolean function IsTriangle(a,b,c)


4.
A Prime Number is a number with only 1 and itself for
divisors.

Write a program using your function to find the primes from 1 to 100.

HINT: a number can be determined to be prime by the following algorithm:

count = 2

prime = true

while count < target and prime

if target % count = 0

then prime = false

else
count++