Programming Concepts
Programming Concepts
ProgrammingBasics
BasicsFor
ForBeginners
Beginners
محمد إبراهيم الدسوقى
محاضر بكلية هندسة و علوم الحاسب – قسم نظم المعلومات
جامعة سلـــمان بن عبد العزيز -السعودية – محافظة الخرج
Email : mohamed_eldesouki@hotmail.com
What Is Programming and Program Development Life
Cycle ?
• Step 3: Maintenance
– Use and modify the program if the problem domain changes
Algorithm:
– Step-by-step problem-solving process
2
The Problem Analysis–Coding–Execution Cycle
3
The Problem Analysis–Coding–Execution
Cycle (cont'd.)
• Run code through compiler
4
The Problem Analysis–Coding–Execution
Cycle (cont'd.)
• Once compiled and linked, loader can place program into main memory
for execution
• Compiler guarantees that the program follows the rules of the language
– Does not guarantee that the program will run correctly
• Binary code:
– A sequence of 0s and 1s
• Byte:
– A sequence of eight bits
6
The Evolution of Programming Languages
LOAD rate
MULT hour
STOR wages
9
The Evolution of Programming Languages
10
The Problem Analysis–Coding–Execution Cycle
Using Any
Programming
Language
11
Then
Think Write Code
12
Basic Definitions
• Programming language:
– a set of rules, symbols, and special words used to write computer
programs.
• Computer program
– Sequence of statements whose objective is to accomplish a task.
• Syntax:
– rules that specify which statements (instructions) are legal
13
Computer System
Input Output
Processing
14
Example 1
• Write a program to find the Area of a rectangle
Input :
Rectangle Length , Rectangle Width.
Processing :
Area = Rect Length * Rect Width.
Output :
Print Out The area.
15
Example 2
• Write a program to find the perimeter and area of a square
The perimeter and area of the square are given by the following formulas:
perimeter = Side Length * 4
area = Side Length * Side Length
Input:
Square Side Length
Processing:
perimeter = Side Length * 4
area = Side Length * Side Length
Output:
Print Out The Perimeter and Area.
16
Your First C++ Program
#include <iostream>
using namespace std;
int main()
{
// This program is written by Mohamed El Desouki
return 0;
}
Sample Run:
My first C++ program.
17
Processing a C++ Program (cont'd.)
• To execute a C++ program:
– Use an editor to create a source program in C++
– Linker:
• Combines object program with other programs provided by the SDK to
create executable code
– Loader:
• Loads executable program into main memory
18
Processing a C++ Program (cont'd.)
19
Interacting With User: Displaying Messages on Screen
• #include <iostream> notifies the preprocessor to include the contents of the input/output
stream header file <iostream> in the program
• We can use the Escape Sequence to format the Displayed Text.
20
Interacting With User: Comments
• /*
Mulitple Lines
• */ to comment multiple lines
21
Example 1
• Write a program to find the Area of a rectangle
Input :
Rectangle Length , Rectangle Width.
Processing :
Area = Rect Length * Rect Width.
Output :
Print Out The area.
22
Central Processing Unit and Main Memory
• In C++ , we use Cin >> Variable; To accept an input from the user.
• To use Cin >>, we must use #include <iostream> ;
• #include <iostream> notifies the preprocessor to include in the program the
contents of the input/output stream header file <iostream>.
• A variable is a location in the computer’s memory where a value can be stored for
use by a program.
• All variables must be declared with a name and a data type before they can be
used in a program.
• Declaration
DataType Identifier;
Int width ;
Float salary ;
24
C++ Data Types
Character or small signed: -128 to 127
char 1byte
integer. unsigned: 0 to 255
signed: -2147483648 to 2147483647
int Integer. 4bytes
unsigned: 0 to 4294967295
signed: -32768 to 32767
short int (short) Short Integer. 2bytes
unsigned: 0 to 65535
signed: -2147483648 to 2147483647
long int (long) Long integer. 4bytes
unsigned: 0 to 4294967295
Boolean value. It can
bool take one of two values: 1byte true or false
true or false.
float Floating point number. 4bytes +/- 3.4e +/- 38 (~7 digits)
Double precision floating
double 8bytes +/- 1.7e +/- 308 (~15 digits)
point number.
Long double precision
long double 8bytes +/- 1.7e +/- 308 (~15 digits)
floating point number.
25
Working With Variable
Cin>>width; area 50
Area = Length * width ;
26
Example 2
• Write a program to find the perimeter and area of a square
The perimeter and area of the square are given by the following formulas:
perimeter = Side Length * 4
area = Side Length * Side Length
Input:
Square Side Length
Processing:
perimeter = Side Length * 4
area = Side Length * Side Length
Output:
Print Out The Perimeter and Area.
27
Declaring & Initializing Variables
• Initialization means to give a variable an initial value.
28
Rules on Variable Names
• DO NOT use reserved words as variable names
(e.g. if, else, int, float, case, for, …).
• The first character has to be a letter or underscore. It can not be a numeric digit.
• The second and the other characters of the name can be any letter, any number, or
an underscore “_”.
Examples
29
Frequently used data types
Data Types Bytes Used • The data type unsigned is used to represent positive
int 4 Bytes integers.
short 2 Bytes • float and double data types for storing real
numbers.
double 8 Bytes
unsigned 4 Bytes The float data type has a precision of seven digits
Float 4 Bytes
- This means after the decimal point you can have seven digits
Double 8 Bytes
Char 1 Byte - Example: 3.14159 534.322344 0.1234567
Example :
-3738.7878787878 3.141592653589790
0.123456789123456
30
Frequently used data types
• We can use Scientific Notation to represent real numbers that are very large or very small in
value.
• The letters e or E is used to represent times 10 to the power.
Example:
• 1.23 x 10 5 is represented as 1.23e5 or 1.23e+5 or 1.23E5
• 1 x 10 -9 is represented as 1e-9
31
Arithmetic Operations
Parentheses are used in C++ expressions in the same manner as in algebraic expressions.
we write a * ( b + c ).
There is no arithmetic operator for exponentiation in C++,
so x2 is represented as x * x.
32
Precedence of arithmetic operations
For example,
2 + 3 * 5 and (2 + 3) * 5
34
Precedence of arithmetic operations
• ? = 1 + 2 * (3 + 4)
35
Data Type of an Arithmetic Expression
• Data type of an expression depends on the type of its operands
– Data type conversion is done by the compiler
36
Data Type of an Arithmetic Expression
Example
int * int; result int
38
Data Type of an Arithmetic Expression
• Only the integer part of the result will be considered if two operands are integer
Even when the target variable is float
39
Type Casting
• Examples :
++K , K++ k= K+1
--K , K-- K= K-1
41
Increment and Decrement Operators
• If the value produced by ++ or – – is not used in an expression, it does
not matter whether it is a pre or a post increment (or decrement).
• When ++ (or – –) is used before the variable name, the computer first
increments (or decrements) the value of the variable and then uses its
new value to evaluate the expression.
• When ++ (or – –) is used after the variable name, the computer uses the
current value of the variable to evaluate the expression, and then it
increments (or decrements) the value of the variable.
x = 5;
Cout << ++x;
x = 5;
Cout << x++; 42
special assignment statements
• C++ has special assignment statements called compound
assignments
+= , -= , *= , /= , %=
• Example:
X +=5 ; means x = x + 5;
x *=y; means x = x * y;
x /=y; means x = x / y;
43
Control Statements
• Normally, statements in a program are executed one after the other in the
order in which they’re written.
• This is called sequential execution.
• There are control statements enable you to specify that the next statement to
be executed may be other than the next one in sequence.
• This is called transfer of control.
45
Selection Statements : If Statement
• Selection statements are used to choose among alternative courses of action.
• For example, suppose the passing mark on an exam is 60. The pseudocode
statement
– If student’s marks is greater than or equal to 60 Then
Print “Passed”
In C++ , The syntax for the If statement
if ( grade >= 60 )
cout <<"Passed\n“;
47
Relational Expression and Relational Operators
• Relational expression is an expression which compares 2 operands and returns a
TRUE or FALSE answer.
Example : a >= b , a == c , a >= 99 , ‘A’ > ‘a’
• Relational expressions are used to test the conditions in selection, and looping
statements.
Operator Means
== Equal To
!= Not Equal To
< Less Than
<= Less Than or Equal To
48
Selection Statements : If Statement
Example : write a program that accept an integer from the user and in case
this integer is even print out the following message
“This number is even “ .
49
Selection Statements : If .. Else Statement
• The IF…Else selection statement allows you to specify that there is a course of
actions are to be performed when the condition is true and another course of
actions will be executed when the condition is false.
else
Print “Failed”
In C++ , The syntax for the If…Else statement
if ( Expression)
action statement ;
Else
action statement ;
if ( Expression)
{
action statements 1 ;
.
action statement n ;
}
Else
{
action statements 1 ;
.
action statement n ;
}
if ( grade >= 60 )
cout <<"Passed\n“;
Else
cout <<“Failed\n” 51
Selection Statements : If – else Statement
Example : write a program that accept an integer from the user and
print out whether it is Positive or Negative number.
52
Nested If
• Nested If : means to write an if statement within another if statement.
Example : write a program that accept an integer number from the user ,
in case the number is Positive , check and print out whether it is Even or Odd
number.
int main()
{
int number;
cout <<"Please Enter any number \n";
cin >>number;
if ( number >=0)
if (number % 2 == 0)
cout <<" This is an Even number \n";
else
cout <<"This is an Odd number \n \n";
}
53
IF – Else IF statement
• For example, write a program that ask the user to Enter 2 numbers and print out
whether they are equal or there is one which is greater than the other.
int main()
{
int num1, num2;
cout <<"Enter Number 1 , Number2 \n";
cin >>num1>>num2;
if ( num1 == num2 )
cout << "Both Are Equal \n";
else if (num1 > num2 )
cout <<"Number 1 is greater than number 2 \n";
else
cout <<"Number 2 is greater than number 1 \n";
} 54
IF – Else IF
• For example, the following code will print
– if ( grade >= 90 )
cout << "A\n“ ;
else if ( grade >= 80 )
cout << "B\n”;
else if ( grade >= 70 )
cout << "C\n”;
else if ( grade >= 60 )
cout << "D\n”;
else
cout << "F\n“ ;
55
Combining more than one condition
• To combine more than one condition we use the logical operators.
56
Combining more than one condition
Example, print out the student grade according to the following formulas:
A for exam marks greater than or equal 90 and less than or equal 100 ,
B for exam marks greater than or equal 80 and less than 90 ,
C for exam marks than or equal to 70 and less than 80 ,
D for exam marks than or equal to 60, and less than 70 ,
F for all other marks.
57
Example : A company insures its Employees in the following cases:
– Employee is married.
– Employee is an Single male above 30 years of age.
– Employee is an Single female above 25 years of age.
– Conditions :
58
Selection statements: Switch Statement.
The switch control statement that allows us to make a decision from the number
of choices
Switch (Expression )
Expression It could be an integer constant like
{ Switch (10.0);
(10);
1, 2 or 3, or an expression that evaluates to an
case constant 1 :
float
Int i ;i ; .
integer
Action statements;
Switch (i);
break ; Constant
Case 50: : is a specific value.
case constant 2 : switch >=
Case ( i +50;
j*k)
Action statements; Case 40 a++10;
b;
break ;
switch ( 23 + 45 % 4 * k )
case constant 3 :
Action statements;
break ;
default :
Action statements;
}
59
60
int i; char ch = 'x' ;
Cin>>I;
switch ( i ) switch ( ch )
{ {
case 10 : case 'v' :
Cout << "I am in case 1 \n“ ; Cout<< "I am in case v \n“ ;
break ; break ;
case 20 : case 'a' :
Cout << "I am in case 2 \n“ ; Cout<< "I am in case a \n“ ;
break ; break ;
case 30 : case 'x' :
Cout << "I am in case 3 \n“ ; Cout<< "I am in case x \n” ;
break ; break ;
default : default :
Cout << "I am in Cout<< "I am in default
default \n“ ; \n„ ;
} }
Expression Possible Forms
switch ( i + j * k )
switch ( 23 + 45 % 4 * k )
61
switch (grade)
{
if ( marks >= 90 && marks <= 100) case 90 :
cout << "A\n“ ; cout <<"You Got A \n"; break;
else if (marks >= 80 && marks <90 )
cout << "B\n”; case 80 :
else if (marks >= 70 && marks <80 ) cout <<"You Got B \n"; break;
cout << "C\n”;
else if (marks >= 60 && marks <70 ) case 70 :
cout << "D\n”; cout <<"You Got C \n"; break;
else
cout << "F\n“ ; case 60 :
cout <<"You Got D \n"; break;
default :
cout <<" Sorry , You Got F \n";
}
62
Switch Versus IF – Else IF
• There are some things that you simply cannot do with a switch. These
are:
– A float expression cannot be tested using a switch
– Cases can never have variable expressions (for example it is wrong
to say case a +3 : )
– Multiple cases cannot use same expressions.
63
Control Statements : Repetition statements
• Some times we need to repeat a specific course of actions either a
specified number of times or until a particular condition is being satisfied.
• For example :
– To calculate the Average grade for 10 students ,
– To calculate the bonus for 10 employees or
– To sum the input numbers from the user as long as he/she enters
positive numbers.
64
1- The While Loop
While ( continuation condition)
{
Action statement 1 ;
Action statement 2 ;
.
.
Action statement n ;
}
66
1- The While Loop
• Example : Write a program that calculates and prints out the Average
grade for 6 students .
int counter = 1;
int grade=0 , sum=0;
while (counter <=6)
{
cout <<"Enter grade for student no " << counter <<"\n";
cin >>grade;
sum += grade;
counter ++;
}
cout <<"Average Grade is " << sum/counter <<"\n";
67
1- The While Loop
• Example : Write a program To print out the sum of the numbers entered
from the user as long as he/she enters positive numbers.
68
1- The While Loop
• Example : Write a program To print out the sum of the numbers entered
from the user as long as he/she enters positive numbers.
while (1)
{
sum += number;
cout <<" Enter Positive numbers to sum \n";
cin>>number;
If (number < 0)
break;
}
69
1- The While Loop
• Example : Write a program that calculates and prints out the Average
grade for 5 students or ends the program by entering -1.
70
2- The do-while Loop
71
2- The do-while Loop
The condition being tested
may be relational, logical or
even numeric expression :
while ( i <= 10 )
while ( i >= 10 && j <= 15 )
While (3) , While (3 + 5)
72
2- The do-While Loop
• Example : Write a program that calculates and prints out the Average
grade for 6 students .
int counter = 1;
int grade=0 , sum=0;
do
{
cout <<"Enter grade for student no " << counter <<"\n";
cin >>grade;
sum += grade;
counter ++;
}
while (counter <=6) ;
73
2- The do-While Loop
74
Control Statements : Repetition statements
• Some times we need to repeat a specific course of actions either a
specified number of times or until a particular condition is being satisfied.
• For example :
– To calculate the Average grade for 10 students ,
– To calculate the bonus for 10 employees or
– To sum the input numbers from the user as long as he/she enters
positive numbers.
75
3- The For Loop.
• For Loop is probably the most popular looping instruction.
• The for allows us to specify three things about a loop in a single line:
(a) Setting a loop counter to an initial value.
(b) testing the loop counter to detect whether its value reached the number
of repetitions desired.
(c) increasing the value of loop counter each time the program segment
within the loop has been executed.
3- The For Loop.
• Example : Write a program that calculates and prints out the Average
grade for 6 students .
77
3- The For Loop.
• Example : Write a program that prints out numbers from 0 to 10;
• Example : Write a program that prints out the even numbers from 2 to 20;
78
3- The For Loop.
• Example : Write a program that accepts 10 numbers from the user and
prints out the sum of even numbers and the sum of odd numbers.
79
3- The For Loop.
int i = 1 ; int i ;
cout<< i ; cout<< i ;
int i = 1 ; int i ;
for ( ; i <= 10 ; ) for ( i = 0 ; ++ i < 10 ; )
{ cout<< i ;
cout<< i ;
i ++;
}
80
3- The For Loop.
• Example : Write a program that calculates the Factorial for any given
positive number.
Ex : Factorial (5) = 5 * 4 * 3 * 2 * 1
81
Nested Loops
• Example : Write a program that calculates the Factorial for numbers from
1 to 10;
82
Nested Loops
• Example : Write a program that prints out the following pattern.
*
**
***
****
*****
******
for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= i ; j++)
cout << "*";
cout << endl;
} 83
Functions
• Most computer programs that solve real-world problems include hundreds and
even thousands of lines.
• Experience has shown that the best way to develop and maintain a large program is
to construct it from smaller pieces or modules, each of which is more manageable
than the original program.
84
In Real Life
In Programming
Task 4
Task 1
Function ( )
Function ( )
Task 3
Task 2
Function ( ) Function ( )
85
Why to use Functions ?
• Functions allows to write more manageable units of code.
• Writing functions avoids rewriting the same code over and over.
• Easy maintenance for programs.
Important Tips
1- Don’t try to cram the entire logic in one function. It is a very bad style of
programming.
2- Instead, break a program into small units and write functions for each of these
isolated subdivisions.
86
Calculate and print out The
sum and the Average of 3
student marks.
Task 4
Task 1
Print_out ( )
Get_Marks( )
Task 3
Task 2
Calc_sum( ) Calc_Average ( )
87
Functions
Function Definition
88
Function Types
1. Built in Functions (Ready Made).
• For Example : Math Library Functions <cmath> Like
89
Built in Functions
To correctly use the built in functions we must know well its header (prortotype).
90
#include <iostream>
#include <cmath>
using namespace std;
int main ( )
{
int i = -5 ;
double x = 5.0;
double y = 2.0;
double z = 5.21;
cout << "The absolute value of i is " << abs (i) << "\n \n";
cout << "The power of x to the power y is " << pow (x,y) << "\n \n";
cout << "The Floor for Z is " << floor (z) <<"\n \n";
cout << "The Ceil for Z is " << ceil (z) <<"\n \n";
}
91
Function Types
2. User Defined Functions ( Tailored by Programmers).
92
Building Functions
1- Function Declaration (Written before The main( ) )
93
User-Defined Functions
• Value-returning functions: have a return type
– Return a value of a specific data type using the return statement
– the returned value can be used in one of the following scenarios:
• Save the value for further calculation
Int result;
Result = sum ( x , y );
98
For Example : write a program that ask the user to Enter 3 integer numbers
and print out their sum and Average.
int main( )
{
int n1 , n2 ;
cout <<"Please Enter 3 integer numbers \n";
cin >>n1 >> n2 ;
cout <<" The sum of the 3 number is " << sum (n1, n2) <<"\n";
}
int sum (int num1 , int num2, int num3 = 90)
{
return num1+ num2+ num3;
}
100
Function Parameters Types
• Value parameter: Reference parameter:
– The value parameter has its own copy of the data
– During program execution, The value parameter manipulates the data
stored in its own memory space. So , the actual parameter not Affected
with any change.
102
Function Parameters Types
103
Scope of a variable
scope is the context within a program in which a variable is valid and
can be used.
result = x + y;
return result; }
} }
104
Scope of a variable
Global variable: declared outside of every function definition.
– Can be accessed from any function that has no local variables with the same
name. In case the function has a local variable with the same name as the
global variable ,
Int z ; GLOBAL
int main ( )
{
{
}
}
int sum (int x , int y )
{
}
105
Scope of a variable
106
Scope of a variable
• Using global variables causes side effects
– If more than one function uses the same global variable and something goes wrong ,
– It is difficult to find what went wrong and where Problems caused in one area of the
program may appear to be from another area.
107
Static and Automatic Variables
• Automatic variable:
108
Static and Automatic Variables
• Automatic variable:
• Static variable:
Static int x;
109
Arrays
• Array : is a collection of fixed number of elements, wherein all
of elements have same data type.
• Array Basics:
– Consecutive group of memory locations that all have the same type.
• One-dimensional array:
– elements are arranged in list form.
• Multi-dimensional array:
– elements are arranged in tabular form.
Arrays
• Syntax for declaring a one-dimensional array:
• Example:
int num[5];
111
Arrays
• Accessing array Elements
Arrayname [element index].
list[5] = 34;
• After declaring the array you can use the For .. Loop to initialize it with values
submmited by the user.
113
• Example : Write a program that ask the user to enter 10 Employee
salaries and store them , then add a bonus of 10 % for each
employee and print out the average salary value.
114
Array Initialization
• Arrays can be initialized during declaration
– In this case, it is not necessary to specify the size of the array
• Size determined by the number of initial values in the braces
115
Array Initialization
int Arr1[5];
int Arr2 [ 5 ] ;
Arr1 = Arr2 ;
116
Array as a Parameter to Function
• Arrays are passed by reference only
• The symbol & is not used when declaring an array as a formal parameter
• The size of the array is usually passed as a parameter to the function.
118
Two Dimensional Array
• Used when data is provided in a table form.
• For Example , to store 4 Marks for 6 students.
M4 M3 M2 M1
Student 1
Student 2
Student 3
Student 4
Student 5
Student 6
119
• Two dimensional Array declaration
1
Float marks [6] [4] ;
2
marks [4][2]= 20 ; 3
4 20
120
Two dimensional Array Initialization
• Consider the declaration
float marks[6][4];
• After declaring the array you can use the For .. Loop to initialize it with
values submmited by the user.
121
Two dimensional Array Initialization
• Two dimensional Arrays can be initialized during declaration
122
• Example : Write a program that build a matrix of 5 rows and 3
columns . As the use to enter the values for all the matrix items ,
print out the sum of all matrix items and print out the sum of the
diagonal items.
123
Two dimensional Array as a Parameter to
Function
when declaring a two-dimensional array as a formal parameter, you can omit
the size of the first dimension, but not the second;
that is, you must specify the number of columns.
124
Struct
• Struct: collection of a fixed number of components (members),
accessed by name
– Members may be of different types.
– For Example : to store a student record which includes different data
items like (student_no , Fname, Lname , Total_Marks , GPA , …….).
Struct Employee
{
int emp_no ;
string fname ;
string lname;
float salary;
float bonus ;
float net_salary;
};
126
Struct
• Once , a new struct is defined , we can use it as any other data type.
int main ()
{
int main ()
{
Employee emp1;
emp1.emp_no = 12;
emp1.fname="Ahmed";
emp1.lname="Ali";
emp1.salary=3000;
emp1.bonus=500;
emp1.net_salary= emp1.salary + emp1.bonus;
}
128
Assignment and Comparison
Value of one struct variable can be assigned to another struct variable
of the same type using an assignment statement
Example :
Employee emp1 , emp2 ;
emp2 = emp1;
copies the contents of emp1 into emp2 ;
129
struct Variables and Functions
• A struct variable can be passed as a parameter by value or by reference.
• A function can return a value of type struct
struct distance_type
{
Int feet ;
float inches;
};
int main ()
{
}
distance_type Add_distances (distance_type d1 , distance_type d2 )
{
distance_type result;
result.feet = d1.feet + d2.feet;
result.inches = d2.inches + d2.inches ;
return result;
} 130
Arrays in structs
struct Student
{
int student_no ;
string sname ;
float GPA;
float marks[3];
};
int main ()
{
Student s1;
s1.student_no = 120;
s1.sname="Ahmed Ibrahim";
s1.GPA= 3.56;
s1.marks[0] = 80;
s1.marks[1] = 70;
s1.marks[2] = 90;
}
131
structs in Arrays
struct Employee
{
int emp_no ;
string fname ;
string lname;
float salary;
float bonus ;
float net_salary;
};
int main ()
{
Employee arr[5];
arr[0].emp_no = 12;
arr[0].fname="Ahmed";
arr[0].lname="Ali";
arr[0].salary=3000;
arr[0].bonus=500;
arr[0].net_salary= arr[0].salary + arr[0].bonus;
} 132
structs within a struct
133
Revision
• Write a program that used to manage The HR data of a department
that has a team of 5 employees . The employee data like ( eno , ename
, job ,salary , bonus). The program should have
134