C - CPP Programming Language - October 2021
C - CPP Programming Language - October 2021
C - CPP Programming Language - October 2021
Introduction to
Programming Using C/C++
Course Duration and Evaluation
• Duration: 60 hours
• 10 Lectures (30 hours)
• 10 Labs (30 hours)
• Evaluation Criteria:
• 40% on labs activities and assignments
• 60% on written exam after 7 days of the last lectures.
• Introduction
• Programming Languages Levels
• Programming Techniques History
• How Do Programming Languages Work?
• C Program Structure
• Some of basics in C Program
• Operators in C
5
11/8/2021 Copyright reserved ITI 2021 5
1.1. Introduction
Algorithms
Instructions
+
Data
Data
Structure
6
11/8/2021 Copyright reserved ITI 2021 6
1.2. Programming Languages Levels
• Low-Level Languages
• Fundamentals language for computer processors,
• 0’s and 1’s that represent high and low electrical voltage (Machine Language),
• Modified to use symbolic operation code to represent the machine operation code (Assembly
Language)
• High-Level Languages
• Use English like statements, executed by operating system (in most cases)
• C, C++, Pascal, Java, ….
• Very High-Level Languages
• Usually domain-specific languages, limited to a very specific application, purpose, or type of
task, and they are often scripting languages
• PLAN, Prolog, LISP
7
11/8/2021 Copyright reserved ITI 2021 7
1.3. Programming Techniques History
8
11/8/2021 Copyright reserved ITI 2021 8
1.3.1 Linear Programming Languages
main
• Programming model that organizes software design around data, or objects, rather
than functions.
• An object can be defined as a data field that has unique attributes and behavior.
• A Class is the template of objects that describe the same data but each one has
different values of attributes.
• Reusability of the classes is one of the advantages of this technique.
• Details will be clear in Object-Oriented Programming using C++ sections …
11
11/8/2021 Copyright reserved ITI 2021 11
1.4. How Do Programming Languages Work?
• Interpreted Languages
• It depends on an interpreter program that reads the source code and translates it
on the fly into computations and system calls- line by line.
• The source has to be re-interpreted (and the interpreter present) each time the
code is executed. Basic and most of scripting languages (HTML)
• Compiled Languages
• Compiled languages get translated into executable file, no need to recompile
again –if there is no changes – run the executable directly. C, C++, Pascal
• Compiled & Interpreted Languages
• Compiler translate to intermediate code and need the interpreter to run that
intermediate code. Java
12
11/8/2021 Copyright reserved ITI 2021 12
1.5. C Program Structure
13
11/8/2021 Copyright reserved ITI 2021 13
1.5.1.1 Include Libraries
• #include
• For using a C function in any program you have to include its library before using. Why it
is in the preprocessing part?
• The compiler needs to check if you call the function in a right way or not: check on the
name and the input parameters (numbers and types).
• Each library consists of C (.c)file and Header File (.h), it is prefer to include the header
file not the C file. Why?
• The compiler check and translate the source code (.c) to executable instructions – system
calls- except the predefined functions in libraries and generate intermediate file called
Objective file (.obj).
• The linker program – as a part of compiler environment – use the libraries –which are
included in the program - to complete the Objective file (.obj) to be an executable file.
How?
14
11/8/2021 Copyright reserved ITI 2021 14
1.5.1.1 Include Libraries
• You can include just one library using one include statement
• Must be the first of the file
• Has two forms:
• #include <stdio.h>
• #include “d:\\myNewLib\\extern.h”
15
11/8/2021 Copyright reserved ITI 2021 15
1.5.1.2 Define and Macro
• #define
• It is used to define a replacement text with another after the statement directly till
the end of the file before starting the compilation.
• Ex:
• #define PI 3.14
• ----
• printf (“%f”, PI); // the replacement done before start compilation the o/p is “3.14”
• Ex:
• #define ONE 1
• #define TWO ONE+ONE
• #define FOUR TWO*TWO
• Macro is another type of text replacement but with using the function operator ().
• Ex:
• #define SUM( X , Y) X+Y
• -------
• -------
• printf(“%d”, SUM(3, 8)); // output will be: 11
• printf(“%d”, SUM(-4, 3)); // output will be: -1
17
11/8/2021 Copyright reserved ITI 2021 17
1.5.1.3 Structures definitions
• Structure mean record with number of fields which they are non-homogeneous in
most cases
• It will be clear in the 3rd lecture.
18
11/8/2021 Copyright reserved ITI 2021 18
1.5.1.4 Global Variables
• The scope of them is global; these variables are accessible by all the functions of
the program.
• It is not preferable to use it without strong reasons; use it if and only if you have to
use it. Why?
• They are saved in a part of the memory sections allocated to the program, this part
is called: Heap Memory
19
11/8/2021 Copyright reserved ITI 2021 19
1.5.1.5 User-defined Functions Prototypes
20
11/8/2021 Copyright reserved ITI 2021 20
1.5.2 Part II: The Main Entry Point: main function
21
11/8/2021 Copyright reserved ITI 2021 21
1.5.3 Part III: User-defined Functions
• It is the part to write the structure of functions you designed it to your program.
• It is the full functions; Header and body for each one.
22
11/8/2021 Copyright reserved ITI 2021 22
1.6. Some of basics in C Program
• Case sensitive.
• Braces, and blocks: {}
• Delimiters after each statements – except include and define: ;
• Basic input and output functions:
• printf
• scanf
• getch or getchar
• clrscr or system(“cls”) ---------> compiler dependent
23
11/8/2021 Copyright reserved ITI 2021 23
1.6. Some of basics in C Program
* The ANSI/IEEE Standard 754-1985 for Binary Floating-Point Arithmetic ("the IEEE standard" or "IEEE 754“)
24
11/8/2021 Copyright reserved ITI 2021 24
1.7. Welcome To ITI World Program
25
11/8/2021 Copyright reserved ITI 2021 25
1.8 Operators in C
26
11/8/2021 Copyright reserved ITI 2021 26
1.8.1 Unary Operators
• It is operators work on just one operand, as follow:
• + : positive sign
• - : negative sign
• ++ : increment operator to increase the value of the operand by 1 unit
• -- : decrement operator to decrease the value of the operand by 1 unit
• ! : Boolean inversion operator; !false=true, !true=false ; !0=1, !1=0 (in C)
• ~ : one’s complement operator; convert to the one’s complement of the operand; 0’s 1’s and
1’s 0’s
• () : casting operator; to change the value of the operand to put it in different data type format
Ex: int x=5; int y;
y = x++; // y = 5 and x = 6
y = ++x; // y = 6 and x = 6
Ex: int x=3, y=5; float f;
f = y / x; // f = 1.0;
f = (float)y/x; // f = 1.66666
27
11/8/2021 Copyright reserved ITI 2021 27
Implicitly (Auto Conversion) and Explicitly casting
Widening
(implicit casting)
Narrowing
(requires explicit casting)
28
11/8/2021 Copyright reserved ITI 2021 28
1.8.2 Arithmetic Operators
• The following table shows all the arithmetic operators supported by the C language. Assume
variable A holds 10 and variable B holds 20 then
29
11/8/2021 Copyright reserved ITI 2021 29
1.8.2 Arithmetic Operators
int x=30600;
5% 2= 1
int y=15236;
5 % -2 = 1 int z=x*y/x;
-5 % 2 = -1
-5 % -2 = -1
Unexpected results
30
11/8/2021 Copyright reserved ITI 2021 30
1.8.3 Relational (Comparison) Operators
• The following table shows all the relational operators supported by C. Assume variable A holds
10 and variable B holds 20 then:
Operator Description Example
== Checks if the values of two operands are equal or not. If yes, then the condition becomes true. (A == B) is not true.
!= Checks if the values of two operands are equal or not. If the values are not equal, then the (A != B) is true.
condition becomes true.
> Checks if the value of left operand is greater than the value of right operand. If yes, then the (A > B) is not true.
condition becomes true.
< Checks if the value of left operand is less than the value of right operand. If yes, then the (A < B) is true.
condition becomes true.
>= Checks if the value of left operand is greater than or equal to the value of right operand. If yes, (A >= B) is not true.
then the condition becomes true.
<= Checks if the value of left operand is less than or equal to the value of right operand. If yes, (A <= B) is true.
then the condition becomes true.
• Note: There is no boolean data type in c; 0 means false and non-zero means true. 31
11/8/2021 Copyright reserved ITI 2021 31
1.8.4 Bitwise (Logical) Operators
• Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |,
and ^ is as follows:
p q p&q p|q p^q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
32
11/8/2021 Copyright reserved ITI 2021 32
1.8.4 Bitwise (Logical) Operators
• The following table lists the bitwise operators supported by C. Assume variable 'A' holds 7 and
variable 'B' holds 5, then
Operator Description Example
& Binary AND Operator copies a bit to the result if it (A & B) = 5, i.e., 0000 0101
exists in both operands.
33
11/8/2021 Copyright reserved ITI 2021 33
1.8.5 Short-Circuit Operators
• Following table shows all the logical Short-Circuit operators supported by C language.
Assume variable A holds 1 and variable B holds 0, then
&& Short-Circuit AND Operator. If left operand equal false the (A && B) is false= 0.
result will be false without check on the right operand.
34
11/8/2021 Copyright reserved ITI 2021 34
1.8.6 Shift Operators
• The following table lists the bitwise Shift operators supported by C. Assume variable 'A' holds
60, then:
<< Binary Left Shift Operator. The left operands value is moved left
by the number of bits specified by the right operand. A << 2 = 240 i.e., 1111 0000
>> Binary Right Shift Operator. The left operands value is moved
right by the number of bits specified by the right operand. A >> 2 = 15 i.e., 0000 1111
35
11/8/2021 Copyright reserved ITI 2021 35
1.8.7 Assignment Operators
• The following table lists the assignment operators supported by the C language:
Operator Description Example
= Simple assignment operator. Assigns values from right side
C = A + B will assign the value of A + B to C
operands to left side operand
+= Add AND assignment operator. It adds the right operand to the
C += A is equivalent to C = C + A
left operand and assign the result to the left operand.
-= Subtract AND assignment operator. It subtracts the right operand
C -= A is equivalent to C = C - A
from the left operand and assigns the result to the left operand.
*= Multiply AND assignment operator. It multiplies the right operand
C *= A is equivalent to C = C * A
with the left operand and assigns the result to the left operand.
/= Divide AND assignment operator. It divides the left operand with
C /= A is equivalent to C = C / A
the right operand and assigns the result to the left operand.
%= Modulus AND assignment operator. It takes modulus using two
C %= A is equivalent to C = C % A
operands and assigns the result to the left operand.
36
11/8/2021 Copyright reserved ITI 2021 36
1.8.7 Assignment Operators
• The following table lists the assignment operators supported by the C language:
37
11/8/2021 Copyright reserved ITI 2021 37
1.8.8 Misc Operators
• There are a few other important operators including sizeof and ternary supported by the C Language.
sizeof() Returns the size of a variable. sizeof(a), where a is float, will return 4.
& Returns the address of a variable. &a; returns the logical address of the variable a.
40
11/8/2021 Copyright reserved ITI 2021 40
Lab Exercise
• Control Statements in C
• Branching Statements
• Looping Statements
• Break Statement
• Continue Statement
• Comments in C
• Introduction to Magic Box Assignment
44
11/8/2021 Copyright reserved ITI 2021 44
2.1 Control Statements
• There are some statements in all of programming languages to control the flow of
the program execution; like conditional statements or repeating statements.
• In C there are two categories of control statements:
• Branching Statements: which has two statements:
• if statement
• switch statement
• Looping Statements: which has three statements:
• for statement
• while statement
• do .. while statement
45
11/8/2021 Copyright reserved ITI 2021 45
2.1.1 Branching Statements
if( Condition(s) )
{ int grade = 48;
…
… //true statements if(grade > 60)
… printf(“Pass”);
} else
[else] {
{ printf(“Fail”);
… }
… //false statements
…
}
46
11/8/2021 Copyright reserved ITI 2021 46
2.1.1 Branching Statements
switch(myVariable){
case value1: • int
… • char
…
break; • enum
case value2:
…
…
break;
default:
…
}
47
11/8/2021 Copyright reserved ITI 2021 47
2.1.1 Branching Statements
• Switch example:
int type;
scanf(“%d”,&type);
switch(type)
{ case 10:
printf(“Perfect”);
break;
case 5:
case 4:
printf(“below avarage”);
break;
default:
printf(“Not accepted”);
} 48
11/8/2021 Copyright reserved ITI 2021 48
2.1.2 Looping Statements (Iteration)
• For statement: The for loop is used when the number of iterations is predetermined.
• Its syntax:
49
11/8/2021 Copyright reserved ITI 2021 49
2.1.2 Looping Statements (Iteration)
• While Statement: The while loop is used when the termination condition occurs unexpectedly
and is checked at the beginning.
• Its syntax:
int x = 0;
while (condition(s))
{ while (x<10) {
… printf(“%d\n”, x);
…
…
x++;
} }
50
11/8/2021 Copyright reserved ITI 2021 50
2.1.2 Looping Statements (Iteration)
• Do .. While Statement: The do..while loop is used when the termination condition occurs
unexpectedly and is checked at the end.
• Its syntax:
do int x = 0;
{
… do{
…
… printf(“%d\n”, x);
x++;
} } while (x<10);
while(condition(s));
51
11/8/2021 Copyright reserved ITI 2021 51
2.2 Break Statement
......
while(age <= 65)
{
……
balance = payment * l;
if (balance >= 25000)
break;
}
......
52
11/8/2021 Copyright reserved ITI 2021 52
2.3 Continue Statement
......
for( year=2000; year<= 2099; year++){
if (year % 4 == 0)
continue;
printf(“Y = %d”, year)
}
......
53
11/8/2021 Copyright reserved ITI 2021 53
2.4 Comments in C
54
11/8/2021 Copyright reserved ITI 2021 54
2.5 Introduction to Magic Box assignment
• You have the following box and need to put the numbers from 1 to 9 in each cell without
repeating and with another constraint: the summation of each row equals to 15 and the
summation of each column equals to 15 and the summation of each diagonal equals to 15.
0 1 2
0 6 1 8
1 7 5 3
2 2 9 4
55
11/8/2021 Copyright reserved ITI 2021 55
2.5 Introduction to Magic Box assignment - Algorithm
• The main constraints:
• The number of rows equal to the number of the columns.
• The order of the box (N) must be odd number; 3X3 or 5X5 or 31X31 and so on.
• The numbers to put in the box start from 1 to NXN
• The algorithm steps:
• Put the number “1” in the middle of the first row
• Repeat the following test for each number to decide the place of the next number starting from
number “1” till number “NXN -1”:
If (CurrentNumber % N !=0 )
{ decrement the current row: with constraint to circulate if necessary
decrement the current column: with constraint to circulate if necessary
}
else
{ increment the current row: with constraint to circulate if necessary
use the same column
}
go to the right place and put the next number
56
11/8/2021 Copyright reserved ITI 2021 56
2.5.1 How to move the cursor in C?
• Some compilers has a function in conio.h library called gotoxy(), and some other has not.
• If your compiler has not this function you may make it in your program as follow:
void gotoxy(int x, int y)
{
COORD coord;
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
• You just write it before the main function for now.
• Note: you will learn how to write a function later.
57
Arrays and Strings
Content
59
11/8/2021 Copyright reserved ITI 2021 59
2.6 Meaning of the array and why do we need it –
Application Level
• An array is a collection of items stored at contiguous memory locations and
elements can be accessed randomly using indices of an array. They are used to
store similar type of elements as in the data type must be the same for all elements.
They can be used to store collection of primitive data types such as int, float,
double, char, or long. And so, an array can store complex or derived data types
such as the structures, another arrays; but from the same types and size.
• Why do we need arrays?
• The idea of an array is to represent many instances of data in one variable while they have a
logical relation among them while this relation can be mapped to indicator to any element of
these instances.
• For example: list of the grads in a subject for group of students in a class: number of student is
an indicator, the grads are the data stored in the array elements
60
11/8/2021 Copyright reserved ITI 2021 60
2.7 Array Characteristics
62
11/8/2021 Copyright reserved ITI 2021 62
2.8 How to declare an array and access it in C:
Abstract Level
Array Declaration in C
63
11/8/2021 Copyright reserved ITI 2021 63
2.8 How to declare an array and access it in C:
Abstract Level
• Accessing Array Elements in C:
• Array elements are accessed by using an integer index. Array index starts with 0 and goes till size of
array minus 1
• Ex:
void main(void)
{ int arr[5];
arr[0] = 5;
arr[2] = -10;
arr[3 / 2] = 2; // this is same as arr[1] = 2
arr[3] = arr[0];
printf("%d %d %d %d", arr[0], arr[1], arr[2], arr[3]); // Output: 5 2 -10 5
}
• Note: There is no index out of bounds checking in C. Why?
64
11/8/2021 Copyright reserved ITI 2021 64
2.9 How the array is implemented in the memory:
Implementation Level
• At first we need to clarify how the compiler declare and store the variables, by generate a
Variables Vector. It may look like the following table:
• Ex: int x; float f
• And so the compiler generate a vector for arrays, it may be look like the following table:
• Ex: int arr[10];
Array Name Type Size Element Size Base Address … …
arr Int 10 2 1000
65
11/8/2021 Copyright reserved ITI 2021 65
2.9 How the array is implemented in the memory:
Implementation Level
• The allocation of the array will be in memory starting from base address –as the address of
first byte allocated to the array- with long of bytes equal to number of elements X element
size. For the above example the base address is 1000 and the size of array in bytes = 10X2 =20
bytes; so the allocated locations for the array in memory from 1000 till 1019 – contiguous -
• The compiler generate an equation to access any element of the array using the index of the
element. It may be look like:
• the address of element with index I = base address + I X element size
• For the above example: the equation will be:
• The address for element indexed with I = 1000 + I X 2
• Ex the address of the fourth element in the array (Index = 3) arr[3] is 1006
address of arr[3] = 1000 + 3 X 2 = 1006
• Note: for the way of array implementation there is no index out of bounds checking in C.
66
11/8/2021 Copyright reserved ITI 2021 66
2.9 How the array is implemented in the memory:
Implementation Level
0 55 1000
int arr[13],x; 1 55 1002
arr[6] = 123; 2 55 1004
X = arr[12]; // x = 55; 3 55 1006
4 55 1008
1010
The address computing: 5 55
6 123 1012
base + index * element size;
7 55 1014
Case arr[6]:
8 55 1016
1000+6*2 = 1012
9 55 1018
Case arr[12]
10 55 1020
1000+12*2= 1024
11 55 1022
12 55 1024
67
11/8/2021 Copyright reserved ITI 2021 67
2.10 Dealing with arrays by looping statements
• Ex:
int i , arr[10];
for(i = 0 ; i < 10 ; i ++)
scanf(“%d”, & arr[i]);
for (i = 9; i >=0 ; i --)
printf(“%d”, arr[i]);
68
11/8/2021 Copyright reserved ITI 2021 68
2.11 Multi-Dimensional Arrays
• Array may be array of arrays, that is mean, to access an array element you have to
use multi-indices: each level of index represent a dimensional level.
• Declaration and accessibility: as two dimensional
• Data_Type Array_Name [Dim1_Size][Dim2_Size];
• Ex: int arr2d [4] [5];
• arr2d[0][0] = 22; // first element
• arr2d [3][4] = 99; // last element
• The Equation for the two-dimensional array:
• the address of element with index A , B = base address + A X 2nd Dim_array_size
+ B X data_element_size
Ex: address of arr2d[1][2] = base address + 1 X (5 X 2) + 2 X 2
• Declaration of N dimension:
• Data_Type Array_Name [Dim1_Size] [Dim2_Size] [Dim3_Size] …. [DimN_Size]; 69
11/8/2021 Copyright reserved ITI 2021 69
2.11 Multi-Dimensional Arrays
0 55 1000
int arr2d[3][4],x ; 1 55 1002
arr2d[1][2] = 123; 0 2 55 1004
x = arr2d[2][3]; 3 55 1006
0 55 1008
3 55 1022
55 1024
70
11/8/2021 Copyright reserved ITI 2021 70
2.12 String
• There is no string data type in C language, the dealing with a string in C is represented by
using a one dimensional array of character.
• In C programming, a string is a sequence of characters terminated with a null character ‘\0’
• There are two ways to declare a string in c language:
• By char array
• By string literal
• Let's see the example of declaring string by char array in C language:
• char str[10]={'C', ‘-', 'P', 'r', 'o', 'g', 'r', 'a', 'm', '\0'};
• As we know, array index starts from 0, so it will be represented as in the figure given below:
0 1 2 3 4 5 6 7 8 9
C - P r o g r a m \0
71
11/8/2021 Copyright reserved ITI 2021 71
2.12 String
• While declaring string, size is not mandatory. So we can write the above code as given
below:
• char str1[]={'C', ‘-', 'P', 'r', 'o', 'g', 'r', 'a', 'm', '\0'};
• We can also define the string by the string literal in C language. For example:
• char str2[]=“C-Program”;
• In such case, '\0' will be appended at the end of the string by the compiler.
• There are two main differences between char array and literal:
• We need to add the null character '\0' at the end of the array by ourself whereas, it is appended
internally by the compiler in the case of the character array.
• The string literal cannot be reassigned to another set of characters whereas, we can reassign the
characters of the array.
72
11/8/2021 Copyright reserved ITI 2021 72
2.12 String
• Notes:
• char str[] = {‘A’, ‘S’, ‘A’, ‘D’}; // is this a String or not?
• char str1 [5] = {‘A’,’L’,’Y’,’\0’}; // is this a String or not?
• char str2 [6] = “Information”; // is this a String or not?
• str2 = “Technology”; // Can we assign a string to array of char after declaration? NO
73
11/8/2021 Copyright reserved ITI 2021 73
2.12 String Manipulation
• Read a string from a user:
• By using scanf(“%s”, str); // problem with spaces
• By using other functions for read lines like: gets(str); // accept the spaces
• Print a string on screen:
• By using printf(“%s”, str);
• By using other functions like: puts(str);
• Functions in string.h: there are many functions like:
• strlen(str) : return the number of characters in the string – before the terminator
• strcat(str1,str2) : concatenation the second string to the first string
• strcpy(destination, source) : copy the source to the destination
• strcmp( str1, str2) : compare between the two strings and return 0, or +ve value or –ve value !!
• 0 : if str1 equals to str2
• +ve: if str1> str2 : if the ASCII value of the first unmatched character is greater than the second and return the
subtraction.
• -ve if str1< str2 : if the ASCII value of the first unmatched character is less than the second and return the
11/8/2021
subtraction. Copyright reserved ITI 2021 74
74
2.12 String Manipulation
• Functions in string.h: there are another functions compiler dependent like:
• strlwr() : converts string to lowercase, found in Borlandc or Turboc
• strupr() : converts string to uppercase, found in Borlandc or Turboc
• strrev(str) : reverse characters of a string, found in Borlandc or Turboc
• strcmpi( str1, str2) : compare between the two strings –case-insensitive- and return 0, or +ve
value or –ve value !!, found in Borlandc or Turboc
• 0 : if str1 equals to str2
• +ve: if str1> str2 : if the ASCII value of the first unmatched character is greater than the second and
return the subtraction.
• -ve if str1< str2 : if the ASCII value of the first unmatched character is less than the second and
return the subtraction.
• strstr(s1, s2) : Find the first occurrence of a substring(s2) in another string (s1), and return the
address of the occurrence if success or return null, found in Borlandc or Turboc.
75
11/8/2021 Copyright reserved ITI 2021 75
2.13 Normal Keys and Extended Keys
• Each key in the keyboard has an ASCII code, which is limited by one byte.
• At the first of computer generation the keyboard was limited not like today; there
was arrows or page up or down of function keys, …. etc.
• So, the new added keys needed ASCII code to be manipulated, so the Extended
Keys are appeared.
• Its ASCII encapsulated in two bytes, the lowest byte equals null and the second
byte has a code.
• When you pressed on an extended key there was 2 bytes are stored in the keyboard
local buffer.
• The following program clarify how to now any key if it is normal or extended and
print its code.
76
11/8/2021 Copyright reserved ITI 2021 76
2.13 Normal and Extended Keys
Void main (void)
{
char ch;
flushall();
printf(“\n Press the key u want to know its type and code”);
ch=getch();
if(ch!=NULL)//Some compilers not accept, replace with -32 or 224
printf(“\nIt is a normal key with code = %d”,ch);
else{
ch=getch();
printf(“\nIt is a Extended key with 2nd byte code = %d”,ch);
}
getch();
77
}
11/8/2021 Copyright reserved ITI 2021 77
Lab Exercise
• Structure Meaning
• Structure definition (Abstract level)
• Structure declaration (Abstract level)
• Accessing Structure Members (Abstract level)
• Structure implementation in the memory (Implementation level)
• Array of Structures
81
11/8/2021 Copyright reserved ITI 2021 81
3.1 Structure Meaning
• Structure is a user-defined datatype in C language which allows you to combine data
of different types together. Structure helps to construct a complex data type which is
more meaningful.
• For example: If I have to write a program to store Employee information, which will
have Employee’s name, age, address, phone, salary etc, which included string values,
integer values etc, how can I use arrays for this problem, I will require something
which can hold data of different types together.
• In structure, data is stored in form of records.
Age float 4 2
Salary float 4 6
deduct float 4 10 1068
Bonus float 4 14
Name char[51] 51 18
69
e1.Salary = 333.3;
The offset of the field ‘Salary’ is added to the address if variable e1to reach to the
address of the field and store the data.
empArr[2].salary = 2315.6;
gets(empArr[3].Name);
scanf(“%f”,&empArr[0].bonus);
empArr[4].Name[2] = ‘T’;
• Note: if we use typedef keyword when defining the structure we can use the alias
name directly without need to use the struct keyword
11/8/2021 Copyright reserved ITI 2021 91
3.6 Array of Structure
• The array of structures initialization can be done by assign the values for each
structure of the array, for example:
struct Employee empArr[2]= {
{10, 35.2, 4500, 234.7, 200, “Hassan Aly”},
{20, 42.3, 7500, 456.3, 450, “Mohsen Ayman”} };
• Modularity
• Function Header and prototype
• Function Parameters and Return Data Type
• Function Body
• Functions Arguments
• Sequence Passing arguments in C
• Recursion and its Constraints
• Introduction to Pointers
• Call by Value and Call by Address
94
11/8/2021 Copyright reserved ITI 2021 94
3.8 Meaning of Modularity
95
11/8/2021 Copyright reserved ITI 2021 95
Function Header, Body, and Prototype
• Function may have no return datatype, and may have no list of input parameters;
write void in both places.
• Function may have no return datatype, and may have list of input parameters; write
void at the beginning of header and write the type and name for each input
parameter.
• Function may have return datatype, and may have no list of input parameters; write
the return data type in the header of function –either primitive or complex- and
void in place of list of input parameters
• Function may have return datatype, and may have list of input parameters; write
the return data type in the header of function –either primitive or complex- and
write the type and name for each input parameter.
99
11/8/2021 Copyright reserved ITI 2021 99
3.10 Parameters and Arguments
• The term parameter refers to any declaration within the parentheses following the
function name in a function declaration or definition; the term argument refers to
any expression within the parentheses of a function call.
• The following rules apply to parameters and arguments of C functions:
• Except for functions with variable-length argument lists, the number of arguments in a function
call must be the same as the number of parameters in the function definition. Or no parameters
nor arguments
• The maximum number of arguments (and corresponding parameters) is 253 for a single
function.
• Arguments are separated by commas. However, the comma is not an operator in this context
• Arguments are passed by value; that is, when a function is called, the parameter receives a copy
of the argument's value
• The scope of function parameters is the function itself. Therefore, parameters of the same name
in different functions are unrelated.
100
11/8/2021 Copyright reserved ITI 2021 100
3.10.1 The sequence of passing the arguments to the function
• We pass different arguments into some functions. Now one questions may come in
our mind, that what the order of evaluation of the function parameters. Is it left to
right, or right to left?
• To check the evaluation order we will use a simple program. Here some parameters
are passing. From the output we can find how they are evaluated.
101
11/8/2021 Copyright reserved ITI 2021 101
Example 2:
#include<stdio.h>
void test_function(int x, int y, int z) {
printf("The value of x: %d\n", x);
printf("The value of y: %d\n", y);
printf("The value of z: %d\n", z);
}
main() {
int a = 10;
test_function(a++, a++, a++);
}
102
11/8/2021 Copyright reserved ITI 2021 102
Example 2:
• From this output we can easily understand the evaluation sequence. At first the z is
taken, so it is holding 10, then y is taken, so it is 11, and finally x is taken. So the
value is 12.
103
11/8/2021 Copyright reserved ITI 2021 103
3.11 The main return values
• The return value for main indicates how the program exited. Normal exit is
represented by a 0 return value from main. Abnormal exit is signaled by a non-zero
return.
• As old fashion in C programming the values 1, 2, or 3 represent abnormal
termination and represent the following state for each value:
• 1 : abnormal exit without saying the reason
• 2 : abnormal exit for memory problem (could not allocate memory, …)
• 3 : abnormal exit for I/O problem (could not change driver mode, …)
• In general the using values are:
• Return 0 for normal exit : like calling function exit(0)
• Return non-zero value for abnormal exit: like calling function exit(1)
104
11/8/2021 Copyright reserved ITI 2021 104
3.12 Recursion
• Recursion is the process of repeating items in a self-similar way. In programming languages,
if a program allows you to call a function inside the same function, then it is called a
recursive call of the function.
• The C programming language supports recursion, i.e., a function to call itself. But while
using recursion, programmers need to be careful to define an exit condition from the
function, otherwise it will go into an infinite loop.
• Recursive functions are very useful to solve many mathematical problems, such as
calculating the factorial of a number, generating Fibonacci series, etc.
• What is the base condition in recursion? In the recursive program, the solution to the base
case is provided and the solution of the bigger problem is expressed in terms of smaller
problems.
105
11/8/2021 Copyright reserved ITI 2021 105
3.12 Recursion
• How a particular problem is solved using recursion? The idea is to represent a problem in
terms of one or more smaller problems, and add one or more base conditions that stop the
recursion. For example, we compute factorial n if we know factorial of (n-1). The base case
for factorial would be n = 1. We return 1 when n = 1.
• Why Stack Overflow error occurs in recursion? If the base case is not reached or not
defined, then the stack overflow problem may arise.
• How memory is allocated to different function calls in recursion? When any function is
called from main(), the memory is allocated to it on the stack. A recursive function calls
itself, the memory for a called function is allocated on top of memory allocated to calling
function and different copy of local variables is created for each function call. When the base
case is reached, the function returns its value to the function by whom it is called and
memory is de-allocated and the process continues.
106
11/8/2021 Copyright reserved ITI 2021 106
3.12.1 Recursion Example: Factorial
• Iteration version:
int Fact( int n)
{
int result=1, i;
for( i = n; i > 1; i--)
result *= I;
return result;
}
107
11/8/2021 Copyright reserved ITI 2021 107
3.12.1 Recursion Example: Factorial
• Recursive version:
int RFact( int n)
{
if (n == 1)
return 1;
return n * Rfact( n-1 );
}
108
11/8/2021 Copyright reserved ITI 2021 108
3.12.2 How to trace a recursive function
RFact(5)= 5 *
RFact(4) = 4 * Rfact(1)
Rfact(3) = 3 * return 1
Rfact(2)
RFact(2) = 2 *
return 2 * Rfact (1)
RFact(1) = 1 Rfact(3)
return 3 * Rfact (2)
Rfact(4)
return 4* Rfact (3)
Rfact(5)
return 5* Rfact (4)
• The following example generates the Fibonacci series for a given number using a
recursive function
#include <stdio.h>
int fib (int i) {
if(i == 1 || i == 2) {
return 1;
}
int main(void) {
int i;
return 0;
}
111
11/8/2021 Copyright reserved ITI 2021 111
3.12.3 Example 2: Fibonacci series
Fib (3) Fib (2) Fib (2) Fib (1) Fib (2) Fib (1)
113
11/8/2021 Copyright reserved ITI 2021 113
3.12.3 Example 2: Fibonacci series sequence of calling
0 Fib (6)
1 10
3 6 8 9 12 13
Fib (3) Fib (2) Fib (2) Fib (1) Fib (2) Fib (1)
4 5
114
11/8/2021 Copyright reserved ITI 2021 114
3.12.4 Advantages and Disadvantages of Recursion
115
11/8/2021 Copyright reserved ITI 2021 115
Lab Exercise
}
11/8/2021 Copyright reserved ITI 2021 136
4.4 Pointer Comparisons
• The output will be as follow:
Address of arr[0] = fff0
Value of arr[0] = 10
Address of arr[1] = fff2
Value of arr[1] = 100
Address of arr[2] = fff4
Value of arr[2] = 200 arr
ptr 10 fff0
0
ptr 1 100 fff2
2 fff4
ptr 200
swap function
3265
5
temp
11/8/2021 Copyright reserved ITI 2021 141
4.6 Using Pointers to call by address: Passing
pointers to functions in C
• The solving of the above problem by using pointer to call the function and pass the
address of the variables as arguments not the values of the variables; Call by address.
As the following function: swap2
void swap2 (int * A, int * B)
{ int temp;
temp = *A;
*A = *B;
*B = temp;
}
• The using of this function will be as follow:
3265
5
temp
return NULL;
}
Shape
draw()
rec1
Rect ShPtr
draw()
squ1
Square
draw()
counter ++; 3
cout<<“This is a constructor with one parameter"<<endl; 2
} 1
~Stack() 0 0
{ top ptr
delete[] ptr; size=0;
counter --;
cout<<"This is the destructor"<<endl;
}
11/8/2021 Copyright reserved ITI 2021 229
6.5 Static Variables and Static Methods
int push(int n);
int pop(int & n);
10
};
9 top
37 9
int Stack::isFull() 8 -13 8
{ 7 21 7
return (top==size) ; 6 63 6
} 5 35 5
4 9 4
int Stack::isEmpty() 3 2 3
{ 2 89 2
return (top==0) ; 1 -3 1
} 0 0 12 0
top ptr
11/8/2021 Copyright reserved ITI 2021
ptr 230
6.5 Static Variables and Static Methods
int Stack::push(int n)
{
if (isFull())
return 0; 9
ptr[top] = n; 8
top++; 7
return 1 6
} 5
//static variable initialization 54 33 4
int Stack::counter = 0; top 11 3
-7 2
25 1
32 0
top top
size size
ptr ptr
top
size
ptr
};
};
11/8/2021 Copyright reserved ITI 2021 259
7.4.1 Mathematical Operator: +
Complex operator+ (float f, Complex & c)
{
Complex temp(f+c.real, c.imag);
return temp;
// return c+f;
}
};
11/8/2021 Copyright reserved ITI 2021 264
7.4.3 Assignment Operators: =
int main()
{
Complex c1(9, 7), c2(13), c3;
c3=c1;
c1.print();
c3.print();
c2=c1=c3;
c1.print();
c2.print();
c3.print();
getch();
return 0;
}
};
11/8/2021 Copyright reserved ITI 2021 266
7.4.3 Assignment Operators: =
int main()
{
Complex c1(9, 7), c2(13), c3;
c2+=c1;
c1.print();
c2.print();
c2=c1+=c3;
c1.print();
c2.print();
c3.print();
getch();
return 0;
}
};
11/8/2021 Copyright reserved ITI 2021 268
7.4.4 Comparison Operators: ==
int main()
{
Complex c1(9, 7), c2(13), c3(9, 7);
cout<<“c1 equals to c3 ? ”<<(c1==c3)<<endl;
if(!(c1==c2))
cout<<“c1 is not equal to c2”<<endl;
getch();
return 0;
}
};
};
end
11/8/2021 Copyright reserved ITI 2021 292
8.2 Collections of objects
• We can deal with objects like the structure, we may crate an array of objects, and we
may make dynamic memory allocation with objects.
• We may initialize the array of objects.
• Dependency: Aggregation implies a relationship where the included object can exist
independently of the container object. For example, Bank and Employee, delete the
Bank and the Employee still exist. whereas Composition implies a relationship where
the included object cannot exist independent of the container object. Example:
Human and heart, heart don’t exist separate to a Human
• Type of Relationship: Aggregation relation is “has-a” and composition is “part-
of” relation.
• Type of association: Composition is a strong Association whereas Aggregation is
a weak Association.
• If a derived class need to access an inherited member which was private in a parent class, it is not
allowed, it has to use the inherited public members which access the private members. If a base class
want to let its derived classes to access its private members directly, it has to put those members in
protected section.
11/8/2021 Copyright reserved ITI 2021 312
9.1.3 Protected Section in Class
• The protected members, which declared in protected section, it is like private
members in the same class, the different in the case of inheritance where the child
class can deal with it directly –by members of the child class not through the objects
of the child class- without need to use the public members. Base Class:
----------------------------
void resetAll(){ Private:
int x
x=0; // Still not accessible use setX() Protected:
int y
y=z=0; // it is ok ----------------------------
public:
a=b=0; int z
setX, setY, getX, gety
}
Derived Class:
• But still x,y, and a not accessible though using Derived class object. ----------------------------
Private:
int a
----------------------------
public:
11/8/2021 Copyright reserved ITI 2021 int b 313
void resetAll()
9.1.4 The Syntax of Inheritance to make a Child Class
class Child_class_name : access-mode Parent_class_name
{
// body of the derived class.
}
• Where,
• Child_class_name: It is the name of the derived class.
• Access mode: The access mode specifies whether the features of the base class are
publicly inherited, protected inherited, or privately inherited. It can be public,
protected, or private.
• Parent_class_name: It is the name of the base class.
• Each part has its initial behavior – constructor- the inherited part
call the constructor of the base class after it is created, and the other
part call the derived constructor after it is created.
Derived
• In the inheritance, the constructors of the base and of the derived Part
are calling in sequential, but in which order?
• The base part is created first, then the constructor of the base class
will calling first, and then the constructor of the derived class is
calling after that.
Base(int n)
{ a=b=n ; }
Base(int x, int y)
{ a = x ; b = y ; }
void setA(int x)
{ a = x ; }
11/8/2021 Copyright reserved ITI 2021 321
9.6 Simple Example of Inheritance
void setB(int y)
{ b = y ; }
int getA()
{ return a ; }
int getB()
{ return b ; }
int calculateSum()
{
return a + b ;
}
};
Derived(int n) : Base(n)
{ c = n ; }
int getC()
{ return c ; }
return 0 ;
}
Protected:
dim1, dim2
Public:
calcArea()
Square
Public:
Square(int)
Square
Rect(float x, float y) : GeoShape(x, y) { } Public:
float calcArea()
{
return dim1 * dim2;
}
};
class Square: public Rect
{ public:
Square(float x) : Rect(x, x) { }
};
11/8/2021 Copyright reserved ITI 2021 329
9.7 The GeoShape Class Hierarchy Example GeoShape
Protected:
dim1, dim2
class Triangle : public GeoShape Public:
calcArea()
{ public:
Circle
Rect Triangle Public:
Triangle(float b, float h):GeoShape(b, h){ } Public: Public: Rect(),
calcArea() calcArea() Rect(int, int)
float calcArea() calcArea()
{ Square
Public:
return 0.5 * dim1 * dim2;
}
};
class Circle : public GeoShape
{ public:
Circle(float r) : GeoShape(r) { }
float calcArea()
{ //it's ok since dim1 equals to dim2.
return 22.0/7 * dim1 * dim2; //you may write: 22.0/7*dim1*dim1.
}
};
11/8/2021 Copyright reserved ITI 2021 330
9.7 The GeoShape Class Hierarchy Example GeoShape
Protected:
dim1, dim2
int main() Public:
calcArea()
{
dim1 = dim2 = length;
}
float calcArea()
{
return dim1 * dim2;
}
};
11/8/2021 Copyright reserved ITI 2021 333
9.7 The GeoShape Class Hierarchy Example GeoShape
Protected:
dim1, dim2
{ public: Circle
Rect Triangle Public:
Public: Public: Rect(),
{ } Square
Public:
Square
Public:
Rect
Geoshape g;
Rect r1;
gptr = & g;
cout<<gptr->calcArea();
gptr = & r1;
cout<<gptr->calcArea(); //the GeoShape version is called
11/8/2021 Copyright reserved ITI 2021 340
10.1 Dynamic (late) Binding and Virtual Function GeoShape
Protected:
dim1, dim2
Public:
calcArea()
r1 GeoShape
virtual Circle Triangle Rect
Public:
calcArea()
gptr Public:
calcArea()
Public:
calcArea()
Rect(),
Rect(int, int)
calcArea()
Square
Public:
Rect
Geoshape g;
Rect r1;
gptr = & g;
cout<<gptr->calcArea();
gptr = & r1;
cout<<gptr->calcArea(); //the Rect version if it is virtual
11/8/2021 Copyright reserved ITI 2021 341
10.1 Dynamic (late) Binding and Virtual Function
class Rect: public GeoShape
{ public:
};
• Multiple inheritance is a type of inheritance in which a class derives from more than one
classes. As shown in the above diagram, class C is a subclass that has class A and class B as
its parent.
• In a real-life scenario, a child inherits from its father and mother. This can be considered as
an example of multiple inheritance.
• What is UML?
• The Unified Modeling Language (UML) is the standard modeling language for
software and systems development.
• Modeling helps you to focus on, capture, document, and communicate the
important aspects of your system’s design.
• A modeling language can be made up of pseudo-code, actual code, pictures,
diagrams, or long passages of description; in fact, it’s pretty much anything that
helps you describe your system.
• The elements that make up a modeling language are called its notation (a way of
expressing the model).
• A modeling language can be anything that contains a notation and a description of
what that notation means.
Class Classes, types, interfaces, and the relationships between them. UML 1.x
The ways in which objects interact and the connections that are Renamed from UML 1.x’s
Communication
needed to support that interaction. collaboration diagrams
11/8/2021 Copyright reserved ITI 2021 369
10.6 Introduction to UML
• UML Diagrams
Originally introduced by
Diagram Type What Can be modeled?
UML 1.x or UML 2.0
Timing Interactions between objects where timing is an important concern. UML 2.0
Package The hierarchical organization of groups of classes and components. UML 2.0
The state of an object throughout its lifetime and the events that can
State Machine UML 1.x
change that state.
Deployment How your system is finally deployed in a given real world situation. UML 1.x
• Visibility
• Visibility describes how a class reveals its operations and data to other classes.
• Once visibility characteristics are applied, you can control access to attributes,
operations, and even entire classes to effectively enforce encapsulation.
• There are four different types of visibility that can be applied to the elements of a
UML model:
• Public Visibility
• Public visibility is specified using the plus (+) symbol before the associated
attribute or operation.
• Declare an attribute or operation public if you want it to be accessible directly by
any other class.
• The collection of attributes and operations that are declared public on a class
create that class’s public interface.
• The public interface of a class consists of the attributes and operations that can be
accessed and used by other classes.
• This means the public interface is the part of your class that other classes will
depend on the most.
• Protected Visibility
• Protected attributes and operations are specified using the hash (#) symbol and are
more visible to the rest of your system than private attributes and operations, but
are less visible than public.
• Declared protected elements on classes can be accessed by methods that are part of
your class and also by methods that are declared on any class that inherits from
your class.
• Package Visibility
• Package visibility, specified with a tilde (~), when applied to attributes and
operations, sits in between protected and private.
• Packages are the key factor in determining which classes can see an attribute or
operation that is declared with package visibility.
• The rule is fairly simple:
if you add an attribute or operation that is declared with package
visibility to your class, then any class in the same package can directly
access that attribute or operation
• Private Visibility
• Private visibility is the most tightly constrained type of visibility classification, and
it is shown by adding a minus (-) symbol before the attribute or operation.
• Only the class that contains the private element can see or work with the data
stored in a private attribute or make a call to a private operation.
• Class Relationships
• Dependency
• The dependency relationship is often used when you have a class that is providing
a set of general-purpose utility functions, such as in Java’s regular expression
(java.util.regex) and mathematics (java.math) packages.
• A dependency between two classes declares that a class needs to know about
another class to use objects of that class.
Student
Mobile Line
Ahmed Loutfy