Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

160
Data Structures - C/C++ Review Prof A Alkhorabi . أ د/ ي ب ور خ ل أ ي عل ه ل ل دأ ب ع

Transcript of Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

Page 1: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

Data Structures

--

C/C++ Review

Prof A Alkhorabi

الخــوربي /دأ. علي عـبدالله

Page 2: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

Data Structures

--

C Review

Prof A Alkhorabi

الخــوربي /دأ. علي عـبدالله

Page 3: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 3Prof A Alkhorabi

C Characteristics

• Size

• Type conversion

• Modern control constructs

• Bitwise control

• Pointer implementation

• Structure

Page 4: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 4Prof A Alkhorabi

C Program Parts

C Program constitutes from 2 parts:

1. Definition, Inclusion & Declaration Part

2. Functions Part

Page 5: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 5Prof A Alkhorabi

1. Definition, Inclusion & Declaration Part

This part have two main sections:

A. C Preprocessor

B. Declaration part

Page 6: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 6Prof A Alkhorabi

A. C Preprocessor

Before compilation the C preprocessor (part of the C compiler) looks for directives (preceded by #), and execute the required task according to the directive type.

There are 3 types of directives:

– include Directive

– define Directive

– conditional compilation Directive

Page 7: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 7Prof A Alkhorabi

include Directive

Includes files to the including file.

include <filename<#

Page 8: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 8Prof A Alkhorabi

define Directive

#define SymbolicName constant

or

#define SymbolicName simple calculation operation

Page 9: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 9Prof A Alkhorabi

Conditional Compilation Directive

�ِAllows writing programs to more than one operating system

#ifdef

Page 10: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 10Prof A Alkhorabi

B. Declaration part

Allow declarations of Global Variables and Functions used later in the program.

Page 11: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 11Prof A Alkhorabi

2. Functions Part • Consists of one or more functions, one of which

must be the main() function.• The C program starts execution from the main()

function, and stops execution by the main() function end.

• The main() function calls other functions, each can call other functions.

Page 12: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 12Prof A Alkhorabi

C Programs Execution

• C program passes through a number of phases starting from the written program by the programmer ( Source File) till it became executable (Executable File).

• This is normally established by Software Systems that are known as Integrated Development Environment (IDE) provided by specialized Software Companies.

Page 13: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 13Prof A Alkhorabi

IDE

• Program Editor

• Preprocessor

• Compiler

• Assembler

• Linker

• IDE’s may include other facilities like Debugging.

Page 14: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 14Prof A Alkhorabi

مراحل برنامج تطوير

Librariesسيالمكتبات

executable code

Editorالمحرر

Preprocessorالم!عد

Assemblerالم!جمع

Linkerالم!دمج

Typing طبع

Source (ASCII) code

Assembly code

Object code

Compilerالم!ترجم

C ProgramDeveloping

Phases

Page 15: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 15Prof A Alkhorabi

C Program Structure/* (1) Inclusion, Definition & Global declarations part */Inclusion partDefinition partglobal declarations part

/* (2) Functions part */return_value main (arguments list)}local declaration partfunction executable statements{

return_value function_2 (arguments list)}local declaration partfunction executable statementsreturned value{::

Page 16: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 16Prof A Alkhorabi

1 /* Sum3.c - Program to sum 3 integers */

2 /* 1- inclusion, definition & glbal vars and functions declaration part */

3 # include “stdio.h” /* a- inclusion part */

4 # define TEN 10 /* b- definition part */

5

6 int sum; /* c-Global Variable & Functions Part */

7

8 /* 2- Functions Part */

9 void main(void) /* main Function */

10 { /* Function opening brace */

11 int num_1, num_2, num_3; /* Local Variables Declaration Part*/

12

13 num_1 = 5; num_2 = 2; num_3 = num_2*TEN;

14 sum=num_1 + num_2 + num_3; /*Function’s Executable Stateent */

15 printf(“The sum of the 3 numbers is %d \n”, sum); /* I/O Lib Func*/

16 } /* Closing Brace */

Page 17: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 17Prof A Alkhorabi

C Reserved Words

• Used within a C program for a specific purposes and according to the language rules, and can not be used in other purposes ( as identifiers for example)

• Consists of two main parts and one sub-part.

Page 18: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 18Prof A Alkhorabi

Reserved Words: 1st main part

• 28 words accompanied the C language from the beginning:

auto break case char

continue default do double

else extern float for

goto if int long

register return short sizeof

static struct switch typedef

union unsigned while entry

Page 19: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 19Prof A Alkhorabi

Reserved Words: 2nd main part

• 5 words added by ANSI (American National Standardization Institute):

const enum signed void volatile

Page 20: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 20Prof A Alkhorabi

• Added by some C Compilers manufacturers:

Asm far _cs fortran huge

near pascal

Reserved Words: Sub-part

Page 21: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 21Prof A Alkhorabi

• All reserved words written using lower-case letters.

Reserved Words: Note

Page 22: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 22Prof A Alkhorabi

Identifies

Used to name and identify:• constants • variables• functions .

• An identifier should not be a reserved word.• Small letters identifiers differ than that written as large letters.

Ex:#define ONE 1int sum;float real(void);

Page 23: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 23Prof A Alkhorabi

• Basic Data Types األساسية البيانات أنواع• Derived Data Types المشتقة البيانات أنواع

• Data Structures البيانات تراكيب

Data Types

Page 24: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 24Prof A Alkhorabi

C Language Have 4 basic data types:

• Integers int.• Single-precision floating numbers float.• Double-precision floating numbers double.• Characters char..

• Void is used to define no type function argument or returned value.

• Ex:void fn(void);

Basic Data Types

Page 25: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 25Prof A Alkhorabi

Integer Variables Types

Type bytes Type Value Range

int 2 -32,768 32,767

unsigned int 2 0 65,535

(ٍshort int 2 -32,768 32,767

long 4 -2,147,483,648 2,147,843,647

unsigned long 4 0 4,294,967,295

Page 26: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 26Prof A Alkhorabi

Integer Operations

Assignment operation Arithmetic operations Relational operations Logical operations Bitwise operations Conditional operator

Page 27: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 27Prof A Alkhorabi

الصحيحة لألعداد العمليات عوامل تنفيذ أسبقيات Integer Operators Precedence

استخدامه طريقة عمله العامل

من اليمين إلى اليسارمن اليمين إلى اليسارمن اليمين إلى اليسارمن اليمين إلى اليسار

نفيمكملتزييد

تنقيص

!

~

++

--

من اليسار إلى اليمينمن اليسار إلى اليمينمن اليسار إلى اليمين

ضربقسمة عدد صحيح

باقي قسمة عدد صحيح

*

/

%

من اليسار إلى اليمينمن اليسار إلى اليمينمن اليسار إلى اليمينمن اليسار إلى اليمين

جمعطرح

إزاحة يساريةإزاحة يمينية

+

-

<<

>>

Page 28: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 28Prof A Alkhorabi

الصحيحة لألعداد العمليات عوامل تنفيذ أسبقيات Integer Operators Precedence

استخدامه طريقة عمله العامل

من اليمين إلى اليسارمن اليمين إلى اليسارمن اليمين إلى اليسارمن اليمين إلى اليسار

من أقليساوي أو من أقل

من أكبريساوي أو من أكبر

<

<=

>

>=

من اليسار إلى اليمينمن اليسار إلى اليمين

نسبي تساوينسبي التساوي

==

!=

من اليسار إلى اليمينمن اليسار إلى اليمينمن اليسار إلى اليمينمن اليسار إلى اليمينمن اليسار إلى اليمينمن اليسار إلى اليمينمن اليسار إلى اليمين

" الثنائية" و" الثنائية" أو

" الثنائية" المقصورة أو" المنطقية" و" المنطقية" أو

الشرطي االنتقاءتخصيص

&

|

^

&&

| |

? =

=

Page 29: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 29Prof A Alkhorabi

Floating-point Variables

The floating-point number 246.66 can be written in one of the following forms:

246.66

24.666× 10(1) 24.666 e 1 24.666 E 1

2.4666× 10(2) 2.4666 e 2 2.4666 E 2

0.024666× 10(4) 0.024666 e 4 0.024666 E 4

24666× 10(-2) 24666 e -2 24666 E -2

Page 30: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 30Prof A Alkhorabi

Floating point Variables

• Single precession real number “float”, 4 bytes.• Double precession real number “double”, 8 bytes. • Long single precession real number “long float”, 8 byes.• Long double precession real number “long double”, 10 bytes.

• long float and double have the same properties.

Page 31: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 31Prof A Alkhorabi

Floating point operations

• Addition uses the operator +• Subtraction uses the operator -• Multiplication uses the operator *• Division uses the operator /

Page 32: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 32Prof A Alkhorabi

Characters

Characters in C Language includes:• Alphabet letters

– Lower case (a,b,c,..)– Upper case (A,B,C,…)

• Digits (0,1,2,...)• Symbols (?,, > , # (,)• Formatting characters, (space, horizontal tabulation,

vertical tabulation).

Page 33: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 33Prof A Alkhorabi

Page 34: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 34Prof A Alkhorabi

Page 35: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 35Prof A Alkhorabi

Characters

• Characters in C are according to ASCII (American National Standard Code for Information Interchange).

• ASCII code also includes transmission characters used for computer network communications (ETX,SYN,... (

Page 36: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 36Prof A Alkhorabi

/* AsciiCharacters.c ASCII Characters Program Example */#include <stdio.h>#include <conio.h>

void main(void){ int x;

for(x = 0; x < 128; x++){ if (x % 20 == 0) getch(); printf("%d\t%c\n",x,x); }

getch(); }

Page 37: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 37Prof A Alkhorabi

Characters

Character variables

char ch;

ch = ‘H’;

Page 38: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 38Prof A Alkhorabi

Character Functions in the Standard Library

• These functions return non-zero integers if it accomplishes their tasks positively, otherwise it returns zeros.

Page 39: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 39Prof A Alkhorabi

القياسية المكتبة في الحروف وظائف

lnum intint(int ch); Is the character ch alphanumeric

isalpha int (int ch); Is the character ch alphabetic

iscntrl int(int ch); Is the character ch a control character

isdigit int(int ch); Is the character ch a digit

int isgraph(int ch); Is the character ch a graphical character

int islower(int ch); Is the character ch a lower case character

isprint int (int ch); Is the character ch a printable character

int ispunct(int ch); Is the character ch a punctuation character

isspace int (int ch); Is the character ch a ‘\f’ , ‘\v’ , ‘\r’ , ‘\n’ , ‘\t’ , ‘ ‘

isupper int(int ch); Is the character ch a upper case character

tolower int (int ch); Change the character to lower case

toupper int (int ch); Change the character to upper case

isxdigit int(int ch); Is the character ch a hexadecimal

Page 40: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 40Prof A Alkhorabi

Character strings

• “This is string 1”

Page 41: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 41Prof A Alkhorabi

Control

In programming languages control is used to determine next statement to be executed.

Normally control can be one of the following types:

Sequential control .

Conditional control.

Iterative control.

Jumping control.

Page 42: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 42Prof A Alkhorabi

Conditional Control

• Conditional control is accomplished by one of the following constructs:

• if-else-if• switch

Page 43: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 43Prof A Alkhorabi

Conditional Control

The if-else-if is used as one of the following forms:• if• if-else• if-else-if

Page 44: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 44Prof A Alkhorabi

if

if (expression) جبري */ /*تعبير

executable_statement(s); /* تعابير مجموعة أو /*تعبير

next_statement;

تعبير اومجموعة تعابير

if

شرط if

التعبير التالي

F

T

if ( x == 5 || y < 8)

printf (“The if conditions that x= 5 OR y < 8 is TRUE” );

Page 45: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 45Prof A Alkhorabi

if- else

ifتعبير

شرط if

التعبير التالي

F

elseتعبير

T

if (expression)

executable_statements_1;

else

executable_statements_2;

next_statement;

Page 46: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 46Prof A Alkhorabi

التالي التعبير

الثالث التعبير

النهائي االختيار تعبيرالنهائي

else-ifالشرط الثالث

F elseالثاني التعبير

else-ifالشرط الثاني

F

F

األول التعبير

if الشرط األول

T

if ( expression_1) statements_1 ;

else if (expression_2) statements_2 ;

else if (expression_3) statements_3;

:

else statements_n ;

next_statement;

if-if- else

Page 47: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 47Prof A Alkhorabi

/* ifelseif.c if-else-if Example Program*/#include <stdio.h>#include <conio.h>

void main(void){ int answer, i = 1; printf("What is the Capital of Yemen (y), UK (u), or Saudia Arabia (s) \n"); answer = getche(); if (answer == 'y' || answer == 'Y' )

printf ( "\n The Capital of Yemen is Sana'a\n\n"); else if (answer == 'u' || answer == 'U' )

printf ( "\n The Capital of UK is London\n\n"); else if (answer == ‘s' || answer == ‘S' )

printf ( "\n The Capital of Saudia Arabia is Riyadh\n\n"); else

printf ( "\n No information is available about this country\n\n"); }

Page 48: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 48Prof A Alkhorabi

switch

switch (expression)

{

case constant_1 : statements_1; break;

case constant_2: statements_2; break; .

:

default: statements_n;

}

next_statement;

Page 49: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 49Prof A Alkhorabi

switch

switch ( جبري( تعبير

breakرابيتعب

التالي التعبير

تطابق هلالحالة الثانية

تطابق هلاألولى الحالة

y

y

N

بيراتع break

N

االختبار تعبيرdefaultالنهائي

Page 50: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 50Prof A Alkhorabi

/* switch.c switch Example Program */#include <stdio.h>#include <conio.h>

void main(void){ int answer, i = 1;

printf("What is the Capital of Yemen (y), UK (u), or Saudia Arabia (s). \n"); answer = getche(); switch ( answer ) { case 'y' : printf ( "\nThe Capital of Yemen is Sana'a\n\n"); break; case 'Y' : printf ( "\nThe Capital of Yemen is Sana'a\n\n"); break; case 'u' : printf ( "\nThe Capital of UK is London\n\n"); break; case 'U' : printf ( "\nThe Capital of UK is London\n\n"); break; case ‘s' : printf ( "\The Capital of Saudia Arabia is Riyadh\n\n"); break; case ‘S' : printf ( "\The Capital of Saudia Arabia is Riyadh\n\n"); break; default : printf ( "\nNo information is available about this country\n\n"); } }

Page 51: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 51Prof A Alkhorabi

Iterative Control

The iterative control can be accomplished by using one of the following constructs:

• while • do-while • for

Page 52: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 52Prof A Alkhorabi

while

while (condition)

{

statement_1;

statement_2;

:

}

next_statement; while( شرط(

التالي حلقة التعبير تعابيرwhile

F

T

Page 53: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 53Prof A Alkhorabi

/* while.c while Example Program */#include <stdio.h>

void main(void){char ch1 = 'a', ch2 = 'A', i = 0;

while ( ch1 <= 'z' ) putchar(ch1++);putchar('\n');while ( ch2 <= 'Z' ) putchar(ch2++);while ( ++i <= 10 ) putchar('\7'); /* Bell */}

Page 54: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 54Prof A Alkhorabi

do-while التركيبdo

{

statement_1;

statement_2;

:

} while (condition);

next_statement;

do

شرطwhile

التعبيرالتالي

الحلقة تعابير

Page 55: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 55Prof A Alkhorabi

• Difference between while and do-while

/* dowhile.c do-while example Program */#include <stdio.h>

void main(void){int i = 0;while ( i ) printf("while succeed\n");do printf("do-while succeed\n");while ( i );}

Page 56: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 56Prof A Alkhorabi

forfor (expression1; expression2; expression3)

executable_statments;

next_statement;

expression1

expression2

executable_statments

expression3

next_statement

• F

• T

expression1 is loop counter initiator

expression2 loop iteration condition

expression3 is loop counter modification

executable_statments are the statements executed in every iteration

next_statement is the statement executed directly after loop termination

Page 57: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 57Prof A Alkhorabi

for

• Exint num;

for (num=0; num < 10; num++)

printf(“The square of [%d] = %d \n”, num, num * num);

printf(“The value of num now is equal to %d n”, num);

Page 58: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 58Prof A Alkhorabi

1. Comma Operator

for (i=0, j=10; i < 20 && i != j; i++){

::

}

Different forms of for

Page 59: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 59Prof A Alkhorabi

2. For without body

Different forms of for

/* for1.c for with multiple expressions Example Program */#include <stdio.h>

void main(void){int i;

for ( i = 0; i < 10; printf("Square(%d) = %d\n", i, i * i), i += 3);}

Output:Square(0) = 0Square(3) = 9Square(6) = 36Square(9) = 81

Page 60: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 60Prof A Alkhorabi

/* for2.c for with no body Example Program */#include <stdio.h>void main(void){int i, j;for(i=0, j=1; i<10 && printf("%d - Square(%d) = %d\n", j++, i, i * i); i+=3);}

Output:1 - Square(0) = 02 - Square(3) = 93 - Square(6) = 364 - Square(9) = 81

Page 61: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 61Prof A Alkhorabi

3. for with empty expressions

Different forms of for

/* for3.c for loop with two empty expressions */#include <stdio.h>

void main(void){int i = 0;for ( ;

i < 10 && printf("Square(%d) = %d\n", i, i * i);

i += 3(;}

The output is the same as for for1.c .

Page 62: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 62Prof A Alkhorabi

Infinite for loopfor ( ; ; );Loop can be stopped only by using “break”

Different forms of for

/* for4.c for as controlled infinite loop, Example Program */#include <stdio.h>void main(void){int i = 0;for ( ; ; ){ if ( i > 10) break; printf("Square(%d) = %d\n", i, i * i); i += 3; }}

The output is the same as for for1.c .

Page 63: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 63Prof A Alkhorabi

for التركيب

Exercise:

Write a C program to output the square of even numbers between 4 and 10.

Page 64: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 64Prof A Alkhorabi

/* for5.c print the square of even numbers between 4 and 10 */#include <stdio.h>void main(void){ int num; for ( num = 4; num <= 10; num++) /* Numbers between 4 - 10*/ { if ( num % 2 == 0 ) /* Even numbers only */

printf("Square(%d) = %d\n", num, num * num); }}

Output:Square(4) = 16Square(6) = 36Square(8) = 64Square(10) = 100

Page 65: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 65Prof A Alkhorabi

Jumping Control

goto

break

Continue

return

exit()

Page 66: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 66Prof A Alkhorabi

goto

goto label; : :label : label_statements;

Page 67: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 67Prof A Alkhorabi

goto

تركيب استخدام الحقائق gotoعند االعتبار في األخذ يجبالتالية:

�من 1. كًال يكون أن لن label, gotoيجب وإال الوظيفة نفس في. مطلوب هو كما القفز من التحكم يتمكن

.2 ) تعبيرات ) مجموعه أو البرنامج labelتعبير تنفيذ سياق ضمن تنفذ ) تستدعى) لم وان أن gotoبواسطة labelالوظيفة يجب ولهذا

موضع كان إن النظر بغض األقل على مرة ذلك من labelيستفادموضع بعد أو .gotoقبل

تكون 3. ما حالة ( labelفي بعد ) داخل gotoوكانت gotoوتعبيرهاموضع من التحكم قفز بعد يتوقف سوف الحلقة تنفيذ فإن حلقة

goto موضع .labelإلى

Page 68: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 68Prof A Alkhorabi

break/* break.c break - Print all i * j if i < j */

#include <stdio.h>

void main(void)

{

int i, j;

for ( j = 1; j <= 5; j++)

{ for ( i = 1; i <= 5; i++)

{ if ( i == j )

break;

printf("\t %d X %d = %d", i, j, i * j );

}

puts ("\n"); }

}

Page 69: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 69Prof A Alkhorabi

• Output

1 X 2 = 2

1 X 3 = 3 2 X 3 = 6

1 X 4 = 4 2 X 4 = 8 3 X 4 = 12

1 X 5 = 5 2 X 5 = 10 3 X 5 = 15 4 X 5 = 20

Page 70: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 70Prof A Alkhorabi

continue /* continue.c continue Example Program*/

/* Print the multiples of 5 from 1 to 30 */

#include <stdio.h>

void main(void)

{

int num;

for ( num = 1; num <= 30; num++)

{ if ( num % 5 != 0 ) /* Multiples of 5 */ continue;

printf("\n %d is a multiple of 5", num ); }

puts ("\n End of for loop - With continue.");

/* The following is the same as the above but with break */

for ( num = 1; num <= 30; num++)

{ if ( num % 5 != 0 ) break;

printf("\n %d is a multiple of 5", num ); }

puts ("\n End of for loop - With break.");

}

Page 71: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 71Prof A Alkhorabi

• Output

5 is a multiple of 5

10 is a multiple of 5

15 is a multiple of 5

20 is a multiple of 5

25 is a multiple of 5

30 is a multiple of 5

End of for loop - With continue.

End of for loop - With break.

Page 72: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 72Prof A Alkhorabi

return

return expression;

Page 73: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 73Prof A Alkhorabi

The function exit()

Declared in stdio.h :

void exit( int return_value);

Page 74: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 74Prof A Alkhorabi

Ex exit()

viod main (void){

:if (salary 0 ) exit (0 ) ;

:}

Page 75: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 75Prof A Alkhorabi

Derived data types

1. Pointers

2. Arrays

3. structures, unions, enumerations and defined types

Page 76: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 76Prof A Alkhorabi

Pointers

• A pointer is a variable that stores the address of another variable.

int x;

Page 77: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 77Prof A Alkhorabi

PointersAddresses of Storing units

1000

1001

1002

1003

:

:

Storing units (bytes)

unit n

unit n+1

unit n+2

unit n+3

:

:

Page 78: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 78Prof A Alkhorabi

Pointers

1000

1002

1003

1004

:

Store of x

Storing units (bytes)Addresses of Storing units

Page 79: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 79Prof A Alkhorabi

Pointers

If a value is assigned to x it will be stored in Store of x

1000

1001

Store of x

5

1002

1003

1004

1005

Page 80: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 80Prof A Alkhorabi

Pointers

• Pointer declaration:type * pointer ;

int x = 5, * ptr ;

Page 81: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 81Prof A Alkhorabi

Pointers المؤشـــرات

• �ِAn address of other variable (x) can be assigned to ptr:

ptr = &x ;

• &x means address of x .

• �ِptr will be assigned the address of x ( 1000)

Page 82: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 82Prof A Alkhorabi

Pointers المؤشـــرات

للمتغير قيمة أي تخصيص سوف 5ولتكن x عند القيمة هذه فأنعنوانه × والذي مقر في RسكQن يمكن 1000ت هذا الذاكرة في

يلي كما : تمثيله1000

1001

Store of x

5

1002

1003 Store of ptr

1004 1000

1005

Page 83: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 83Prof A Alkhorabi

/* ptr1.c pointers Example Program*/#include <stdio.h>void main(void){int x = 5, y = 17, *ptr1, *ptr2;*ptr1 = x;ptr2 = &y;printf("Value of x is %d, and its address in memory is %lu.\n", *ptr1, (long)ptr1);

printf("ptr1 points to %d.\n", *ptr1);printf("Value of y is %d, and its address in memory is %lu.\n", *ptr2, (long)ptr2);

printf("ptr2 points to %d.\n", *ptr2);x = *ptr2;printf("Value of x now is %d.\n", x);ptr1 = ptr2;printf("What ptr1 points to now is %d.\n", *ptr1);}

Page 84: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 84Prof A Alkhorabi

Pointers Multiple Indirection

1000 num

1001 5

1002

1003

1004

1005 ptr1

1006 1000

1007

1008

1009

1010 ptr2

1011 1005

1012

Page 85: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 85Prof A Alkhorabi

Pointers Multiple Indirection

/* ptr2.c Pointers Multiple Indirection */# include <stdio.h>void main (void){int num = 5, *ptr1, **ptr2; /*ptr2 is a pointer to pointer to

integer*/ptr1 = &num;ptr2 = &ptr1;printf(“number = %d”, **ptr2);}

Page 86: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 86Prof A Alkhorabi

Pointers Initiation

• Give an address to a pointer, if known, otherwise give it the value NULL which is known by the compiler

Page 87: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 87Prof A Alkhorabi

Arrays

• An array is one of the derived data types.• An array consists of a number of elements of the same

type.• Number of an array elements is declared before using

the array.

Page 88: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 88Prof A Alkhorabi

Arrays

• Array Declarationtype array_name[no_of_elements] ;

int class1[4] ;

class1[0] = 34 ;

Page 89: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 89Prof A Alkhorabi

/* array1.c Array Example - Find the largest and smallest array elements */

#include <stdio.h>

void main(void){int num[10]; /* array declaration */int i, max, min;puts(" Program to find the largest and the smallest array elements.");

/* Fill array elements */for ( i = 0; i < 10; i++){ printf ( "Enter an integer: array element number %d\n", i); scanf("%d", &num[i]); }

Page 90: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 90Prof A Alkhorabi

/* array1.c Array Example - Continue *//* assign to min & max the value of the first array element */min = max = num[0];/* Find min & max array elements */for ( i = 0; i < 10; i++){ if ( num[i] > max ) max = num[i]; else if ( num[i] < min ) min = num[i]; }

printf("The largest array element is %d\n", max);printf("and the smallest array element is %d", min); }

Page 91: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 91Prof A Alkhorabi

Arrays in Memory

1000 Class1

[0]

1002 Class1

[1]

1004 Class1

[2]

1006 Class1

[3]

First Element Second Element Third Element Fourth Element

Page 92: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 92Prof A Alkhorabi

Assignment for Array Elements

Direct Assignment • num[0] = 10;

• num[1] = 12;

• num[2] = 15;

• num[3] = 20;

Assignment could be done when declaring the array itself:

• int num[5] = {3, 15, -7, 10, 1};

• char string[9] = {“a string”};

Page 93: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 93Prof A Alkhorabi

Assignment for Array Elements

Indirect Assignment • An array name is a pointer always points to its first element

int num[4];

num[0] num[1] num[2] num[3]

num

Page 94: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 94Prof A Alkhorabi

Assignment for Array Elements

• Indirectly the name of the array (pointer) is used to access all the array elements

*num = 10;

*(num+1) = 12;

*(num+2) = 15;

*(num+3) = 20;

Page 95: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 95Prof A Alkhorabi

/* array2.c Arrays Example Program *//* Pointers & Array elements */#include <stdio.h>void main(void){int num[4] = {10, 12, 15, 20};

printf("Array elements are %d %d %d %d", *num, *(num+1), *(num+2), *(num+3));

}

• OutputArray elements are 10 12 15 20

Page 96: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 96Prof A Alkhorabi

Character Arrays and Strings

• “This is a string.”• The following is a character array that accommodates a

string of character

‘T’ ‘h' ‘i’ ‘s’ ‘ ‘ ‘i’ ‘s’ ‘ ‘ ‘a’ ‘ ‘ ‘s’ ‘t’ ‘r’ ‘i’ ‘n’ ‘g’ ‘.’ ‘\0’

Page 97: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 97Prof A Alkhorabi

Strings Operations

• A number of string operations in the Standard library are declared in string.h.

Page 98: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 98Prof A Alkhorabi

Strings Operations

int strcmp (const char *s1, const char *s2);

char *strcpy (char *s1, const char *s2);

char *strcat (char *s1, const char *s2);

int strlen (const char *s);

int strncmp (const char *s1, const char *s2, int n);

char *strncpy (char *s1, const char *s2, int n);

char *strncat (char *s1, const char *s2, int n);

char *strch (const char *s, int ch);

char *strstr (const char *s1, const char *s2);

Page 99: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 99Prof A Alkhorabi

/* array3.c String array operations */#include <stdio.h>#include <string.h>void main(void){char s1[80] = "This is a string", s2[40] = "this is another string", *ptr;printf("There are %d characters in s1, and %d characters in s2.\n",

strlen(s1), strlen(s2));if ( strcmp(s1, s2) > 0) puts("s1 > s2.\n ");else if ( strcmp(s1, s2) == 0) puts("s1 is equal to s2.\n ");else puts("s1 < s2.\n ");

Page 100: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 100Prof A Alkhorabi

/* array3.c String array operations - Continue */strcat (s1, " and "); strcat (s1, s2);printf ("%s\n", s1); strcat ( s1, ", there are two strings now."); printf("%s\n", s1);if ( ptr = strstr ( s1, "two") ) /*if ptr value is not NULL*/ printf("%s\n", ptr );if ( (ptr = strstr ( s1, "This is not the same string"))) puts("It seems ptr has a

value !!!\n");else puts ("ptr has a NULL value.\n");}

Page 101: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 101Prof A Alkhorabi

• OutputThere are 16 characters in s1, and 22 characters in s2.

s1 < s2.

This is a string and this is another string

This is a string and this is another string, there are two strings now.

two strings now.

ptr has a NULL value.

Page 102: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 102Prof A Alkhorabi

type array [row][column];

int student[5][3];

Two-dimensional arrays

Page 103: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 103Prof A Alkhorabi

The two-dimensional array student can be visualized as shown

Two-dimensional arrays

student[3][1] = 150 1 2

0

1

2

3 15

4

Page 104: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 104Prof A Alkhorabi

/* array6.c Two-dimensional array */#include <stdio.h>#include <string.h>void main(void){ int row, col, sum, student[5][3] = { {90, 75, 80},

{85, 80, 90}, {83, 82, 75}, {60, 72, 73}, {65, 68, 70} };for ( row = 0; row < 5; row++){ sum = 0; for ( col = 0; col < 3; col++ ) sum += student[row][col]; printf ( "Average degrees of student ( %d ) is %d\n", row +1, sum/3);}}

Page 105: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 105Prof A Alkhorabi

Output:Average degrees of student ( 1 ) is 81

Average degrees of student ( 2 ) is 85

Average degrees of student ( 3 ) is 80

Average degrees of student ( 4 ) is 68

Average degrees of student ( 5 ) is 67

Page 106: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 106Prof A Alkhorabi

• Structures

• Unions

• Enumeration

• Defined Types

Page 107: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 107Prof A Alkhorabi

Structures

• Structures consists of members of different types• Structures are used to represent objects that have a

variety of properties (specifications)• An object could be a person, animal, state, or a thing

Page 108: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 108Prof A Alkhorabi

Structures Declarationstruct structure_name{ type member_1; type member_2;

:};

Page 109: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 109Prof A Alkhorabi

Structures Declaration

• Ex: Studentstruct date{ int day; int month; int year;};

struct student{ char name[30]; int department; int level; struct date date_of_birth;};

Page 110: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 110Prof A Alkhorabi

Structure Variables Declaration

• Direct method:struct student{ :

: } stud_1 , stud_2 ;

Page 111: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 111Prof A Alkhorabi

Structures Variables Declaration

• Indirect method:• First declare the structure

struct student

{

:

} ;

• Later somewhere else in the program declare the structure variables

struct student stud_1 , stud_2 ;

Page 112: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 112Prof A Alkhorabi

Structure members assignment

• Direct method:struct student stud_1;

stud_1.department = 1;

stud_1.level = 3;

• The student represented by stud_1 is in department 1 (Computer for example) and in level 3

Page 113: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 113Prof A Alkhorabi

Structure members assignment

• Indirect method:struct student *ptr;

ptr = &stud_1;

ptr -> department = 1;

ptr -> level = 3;

• Also this means that the student represented by stud_1 is in department 1 (Computer for example) and in level 3

Page 114: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 114Prof A Alkhorabi

/* struct1.c Structures - members accessing */#include <stdio.h>#include <string.h>struct date{

int day;int month;int year;

};struct student{

char name[30];int department;int level;struct date date_of_birth;

};

Page 115: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 115Prof A Alkhorabi

/* struct1.c Structures - members accessing - Continued */struct student stud_1, *std_ptr, class1[2];void read_students_data(void);void write_students_data(void);void write_student_data_using_pointers(void);

void main(void){printf("%d %d %d %lu %lu\n",

sizeof(stud_1), sizeof(*std_ptr), sizeof(*class1), sizeof(std_ptr), sizeof(class1) );

read_students_data();write_students_data();write_student_data_using_pointers(); }

Page 116: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 116Prof A Alkhorabi

/* struct1.c Structures - members accessing - Continued */void read_students_data(void){int i;char full_name[30];for ( i = 0; i < 2; ++i ){ printf("\nEnter data of student %d :\n", i + 1); puts("\tstudent name : First Middle Last (names)\n"); gets(full_name); strcpy(class1[i].name, full_name); puts(" \n\tstudent department(int) "); scanf("%d", &class1[i].department); puts(" \n\tstudent level(int) "); scanf("%d", &class1[i].level); printf("\n\tstudent date of Birth Day(int), Month(int) and Year(int)"); scanf("%d%d%d", &class1[i].date_of_birth.day, &class1[i].date_of_birth.month, &class1[i].date_of_birth.year); fflush ( stdin ); } }

Page 117: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 117Prof A Alkhorabi

/* struct1.c Structures - members accessing - Continued */void write_students_data(void){int i;for ( i = 0; i < 2; i++ ){ printf("Data of student %d :\n", i + 1); printf("\tstudent name : %s \n", class1[i].name); printf("\tstudent department : %d\n", class1[i].department); printf("\tstudent level : %d\n", class1[i].level); printf("\tstudent date of Birth : %d\\%d\\%d \n\n", class1[i].date_of_birth.day,

class1[i].date_of_birth.month, class1[i].date_of_birth.year);

} }

Page 118: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 118Prof A Alkhorabi

/* struct1.c Structures - members accessing - Continued */void write_student_data_using_pointers(void){int i = 1;std_ptr = class1; /* could be written std_ptr = &class[0]; */

while( std_ptr && i < 3 ) /* while std_ptr is not equal to NULL*/{ printf("Data of student %d :\n", i++ ); printf("\tstudent name : %s\n", std_ptr->name); printf("\tstudent department : %d\n", std_ptr->department); printf("\tstudent level : %d\n", std_ptr->level); printf("\tstudent date of Birth : %d\\%d\\%d \n\n", std_ptr->date_of_birth.day,

std_ptr->date_of_birth.month, std_ptr->date_of_birth.year); ++std_ptr; }}

Page 119: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 119Prof A Alkhorabi

• Directlystruct student stud_1, stud_2, *ptr1, *ptr2;

stud_1.department = 3;

stud_2 = stud_1;

printf (“%d”, stud_2.department);

Assigning a structure variable to Another

Page 120: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 120Prof A Alkhorabi

• Directlystruct student stud_1, stud_2, *ptr1, *ptr2;

prt1 = & stud_1;

ptr1 = & stud_1;

ptr2 = ptr1;

Assigning a structure variable to Another

Page 121: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 121Prof A Alkhorabi

/* struct2.c Structure assignment */#include <stdio.h>struct student{ char name[20];

int department;int level; };

void main(void){ struct student stud_1, stud_2, *ptr1, *ptr2;

stud_1.department = 3;stud_2 = stud_1;ptr1 = &stud_1;ptr2 = ptr1;printf("department = %d.\ndepartment = %d.\ndepartment \= %d.\ndepartment = %d.", stud_1.department,stud_2.department, ptr1->department,ptr2->department ); }

Page 122: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

Data Structures

--

C++ Review

Prof A Alkhorabi

الخــوربي /دأ. علي عـبدالله

Page 123: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 123Prof A Alkhorabi

C/C++ Similarities

• Comments /* …. */• Basic Data Types (Objects)• Operators• Operator Precedence• Declarations and Definitions• Program Structure• Assignment• Identifiers • Program Control

Page 124: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 124Prof A Alkhorabi

// Program: Display greetings// Author: A Alkhorabi// Date: 11/10/2009

#include <iostream> // or <iostream.h>

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

A First Program - Hello.cpp

Preprocessor directives

InsertionStatement-o/p

Ends executionsof main() which ends

program

Comments

Function named main()

indicates start of

program

Page 125: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 125Prof A Alkhorabi

Greeting Output

Page 126: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 126Prof A Alkhorabi

C++ Objects• In C++ (OOP) all of the following are considered

objects:– Constants– Variables– Objects (of classes)

Page 127: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 127Prof A Alkhorabi

Const Definitions• Modifier const indicates that an object cannot be changed

– Object is read-only

• Useful when defining objects representing physical and mathematical constants

const float Pi = 3.1415;

• Value has a name that can be used throughout the programconst int SampleSize = 100;

• Makes changing the constant easy– Only need to change the definition and recompile

Page 128: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 128Prof A Alkhorabi

C++ Classes

Object-Oriented ProgrammingUsing C++

Page 129: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 129Prof A Alkhorabi

Outline

• Class Declaration

• Access Control

• Constructors and Destructors

• Instance Declaration

Page 130: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 130Prof A Alkhorabi

Class Declaration

class ClassName {

private:

// hidden declarations go here

public:

// interface visible to the user goes here

};

Page 131: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 131Prof A Alkhorabi

Access Control

• Private– Prevent access outside of class

– Primarily attributes (data), some methods

• Public section– Declare interface (usually only methods-functions)

– Usable anywhere outside of class

Page 132: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 132Prof A Alkhorabi

Constructors• Responsible for initializing new objects• Default: ClassName(); // Empty parameters• Copy: ClassName(const ClassName& C);• User named: ClassName(char* name);

Ex:class Frame // Window class{ private:

public:

};

Page 133: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 133Prof A Alkhorabi

Object (Instance) Declaration

• Use class name like built-in type

• Declaration may use different constructors– Frame fstWindow; // uses default

– Frame scdWindow(fstWindow); // copy

– Frame thdWindow(“Third”); // user

• When declaration comes in scope, object created.

Page 134: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 134Prof A Alkhorabi

Constructors and Initialization

• Sequence of object creation:1. Create storage for object

2. Initialize storage

3. Perform body of constructor

Page 135: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 135Prof A Alkhorabi

Destructors

• Responsible for properly destroying object

• Prototype: ~Frame()

• Declare one even if you don’t need it:

~Frame() {}

• Important when have pointers as field

Page 136: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 136Prof A Alkhorabi

(Other) Methods

• Declare prototypes in class declaration

int hasName(char *nme);

• Note: no return type for constructors and destructors

• Using methods– Inside class: hasName()

– Outside class: fstWindow.hasName();

Page 137: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 137Prof A Alkhorabi

Parameters

• Pass-by-value

int hasName(string nme);

• Pass-by-reference

int hasName(string& nme);

• What happens when pass complex object by value?

Page 138: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 138Prof A Alkhorabi

Matters of Necessity

If you want to use your class like a built-in type, you must include– A default constructor

– A copy constructor

– An assignment operator

– A destructor

Page 139: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 139Prof A Alkhorabi

// constr1.cpp// Constructor & Destructor Example - constr1.cpp// Dynamic Objects Allocation & Deletion Application #include <iostream.h>#include <string.h>

class student{

char *name;int department, level;

public :student(int sz); // Constructorvoid get_stud(void);void show_stud(void);~student(); // Destructor

};

Page 140: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 140Prof A Alkhorabi

student::student(int sz){ name = new char[sz]; }

void student::get_stud(void){ strcpy(name, "Ahmed Hussien");department = 2;level = 3;}

void student::show_stud(void){ cout << "Student name : " << name

<< "\nDepartment : " << department << "\nLevel : " << level; }

student::~student(){ delete name; }

Page 141: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 141Prof A Alkhorabi

int main(void){ student stud(30); // Declare a stud object - Constuctor

// & allocate memory to it. stud.get_stud(); stud.show_stud();

return 0;}

OutputStudent name : Ahmed Hussien Department : 2Level : 3

Page 142: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 142Prof A Alkhorabi

ClassesInheritance

Mechanism for deriving new classes from existing classes

Page 143: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 143Prof A Alkhorabi

Inheritance

• Be able to create specialized objects without starting from scratch

• Inheritance is the object-oriented programming mechanism for specialization

Page 144: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 144Prof A Alkhorabi

ShapesHierarchy

C: ShapeDM: Color

MF: GetColor(), SetColor()

C: RectangleShapeDM: Width, Height

MF: Draw(), GetWidth(),GetHeight(), SetSize()

C: TriangleShapeDM: SideLength

MF: Draw(),GetSideLength(),

SetSize()

C: WindowObjectDM: Location, Window

MF: GetPosition(), GetWindow(), SetPosition()

C: Label

C: EllipseShapeDM: Width, Height

MF: Draw(),GetWidth(),

GetHeight(), SetSize()

Page 145: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

Prof A Alkhorabi

Defining a Derived Class

class DerivedClass : public BaseClass { private:

// private section ... public:

// public section ...};

Derived class name

Access specifier(usually public)

Class name ofbase class

Page 146: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

Prof A Alkhorabi

Declaring a Derived Class

class Shape : public WindowObject {

private:

color Color;

public:

Shape(SimpleWindow &w,

const Position &p,

const color &c = Red);

color GetColor() const;

void SetColor(const color &c);

};

Read this as Shape is a kind of WindowObject

Shape inherits WindowObjectmembers Window, Location,GetPosition(), GetWindow(),and SetPosition()

Page 147: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

Prof A Alkhorabi

Inheritance and Member Access

class SomeClass {private:

int MyPrivateData;protected:

int MyProtectedData;public:

void MemberFunction();int MyPublicData;

};

void SomeClass::MemberFunction() {MyPrivateData = 3; // access allowedMyProtectedData = 2; // access allowedMyPublicData = 1; // access allowed

}

Page 148: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

Prof A Alkhorabi

Inheritance and Member Access

void NonMemberFunction() {SomeClass C;C.MyPrivateData = 3; // illegalC.MyProtectedData = 2; // illegalC.MyPublicData = 1; // access allowed

}

Page 149: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

Prof A Alkhorabi

Inheritance and Member Access

class BaseClass {public: int MyPublicData;protected: int MyProtectedData;private: int MyPrivateData;

};

class DerivedClass : public BaseClass {public: void DerivedClassFunction();// ...

};

void DerivedClass::DerivedClassFunction() {MyPrivateData = 3; // illegalMyProtectedData = 2; // access allowedMyPublicData = 1; // access allowed

}

Page 150: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 150Prof A Alkhorabi

Accessed by

Class Members

Basic Class Members

Derive Classes

Class Objects

Private members

Protected members

Public members

Yes

Yes

Yes

No

Yes

Yes

No

No

Yes

Page 151: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 151Prof A Alkhorabi

// inhert0.cpp// Inheritance (Single and Multi level) Example#include <iostream.h>#include <string.h>

class A // Base Class{ // Base class private members are inaccessable by drived class members protected :

int a1, a2; public :

void fnA1(void) {cout << "From class A : Data members ; a1 & a2\n";}

void fnA2(void) { cout << "From class A : Function members ; fnA1() & fnA2()\n"; }};

class B : public A // Derived Class{ protected : int b1, b2; public : void fnB(void) { cout << "From class B : Data members ; b1 & b2\n“

<< "From class B : Function member ; fnB()\n"; }};

Page 152: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 152Prof A Alkhorabi

class C : public B // Derived Class

{

protected :

int c1;

public :

void fnC(void) {

cout

<< "From class C : Data member ; c1\n"

<< "From class C : Function member ; fnC()\n";

}

};

Page 153: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 153Prof A Alkhorabi

int main(void){A a; B b; C c;

cout << "Class A has access to the following mambers :\n"; a.fnA1(); // Base class(A) member function a.fnA2(); // Base class(A) member function cout << "\n"; cout << "Class B has access to the following mambers :\n"; b.fnA1(); // Base class(A) member function b.fnA2(); // Base class(A) member function b.fnB(); // Derived class(B) member function cout << "\n"; cout << "Class C has access to the following mambers :\n"; c.fnA1(); // Base class(A) member function c.fnA2(); // Base class(A) member function c.fnB(); // Derived class(B) member function c.fnC(); // Derived class(C) member function return 0; }

Page 154: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 154Prof A Alkhorabi

Output Class A has access to the following members :From class A : Data members ; a1 & a2From class A : Function members ; fnA1() & fnA2() Class B has access to the following members :From class A : Data members ; a1 & a2From class A : Function members ; fnA1() & fnA2()From class B : Data members ; b1 & b2From class B : Function member ; fnB()

Class C has access to the following members :From class A : Data members ; a1 & a2From class A : Function members ; fnA1() & fnA2()From class B : Data members ; b1 & b2From class B : Function member ; fnB()From class C : Data member ; c1From class C : Function member ; fnC()

Page 155: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 155Prof A Alkhorabi

Polymorphism

• A polymorphism is a form of generalization

• Allows reuse of code within a program– Only have to write one

• List class

• Sort function

• Binary search tree class

Page 156: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 156Prof A Alkhorabi

Polymorphism in C++

• Polymorphic functions– Through inheritance

– Operator overloading

• Polymorphic types– Template classes

Page 157: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 157Prof A Alkhorabi

Inheritance Relationship

• Classes may “inherit” properties from others

• Ex. A dog is a mammal

• Inheritance defines a hierarchy of classes

Page 158: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 158Prof A Alkhorabi

Inheritance Terminology

• Base, super- or parent class

Refers to class inherited from

• Derived, sub-, or child class

Refers to class which inherits

Page 159: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 159Prof A Alkhorabi

Subtypes

• We want inheritance to reflect a subtype relationship

• Ex.– A dog is a mammal

– An integer is a real number

– The numbers 0-9 are integers

• Subtypes share properties (operations) with supertype

Page 160: Data Structures -- C/C++ Review Prof A Alkhorabi أ.د/ عـبدالله علي الخــوربي.

0.3- 160Prof A Alkhorabi

Polymorphism and Subtypes

• A subtype can be used anywhere a supertype can be– Ex. An integer in the range 0-10 can be used

anywhere an integer can be used– Ex. An integer can be used anywhere a real

number can be used

• Defining a function on supertypes allows us to use it on the subtypes

• Limited form of polymorphism