1fp2023
1fp2023
1 Class
2023-2024
Programming Fundamentals
أساسيات البرمجة
أساتذة المادة :أ.م.د .بشار سعدون
م.انمار علي
م .ياسر منذر
م.م .رشا اسماعيل
LECTURE 1
1.. I 11\,tro Cit uctLo V'v:
Monitor
(Output Device)
,.........c.......a..JL..J.<c....a....a,..._. -
RAM
(Main Memory)
hardware components
2. s~ort tttstoq_j:
The following is a short history, just for given a general view of how languages
are arrived:
• 1954: Fortran.
• 1957: Cobol.
• 1958: Algol (Base for Simula).
• 1958: Lisp.
• 1961 : B1000.
• 1962: Sketchpad.
• 1964: Basic.
• 1967: Simula67.
• 1968: FLEX.
• 1970: Pascal (From Algol).
• 1971: C {From a language called B).
• 1972: Smalltalk72 (Based on Simu/a67 and Lisp).
• 1976: Smalltalk76.
• 1979: ADA (From Pascal).
• 1980: C with dasses {experimental version}.
• 1983: C++ (by Bjarne Stroustrup).---------1
• 1986: Objective-C (from C and Smalltalk).
• 1986: Eiffel (from Simula).
• 1991 : Sother (From Eiffel).
• 1991: Java.
Bjarne Stroustrup
• 2000: C#. at: AT& Hobs
3. c+ + Progrcu ,1tVlA-[V\.,g LaV\.,gutAge:
1
I Err<M" Messages I
_______.. q~~ _______
Other Object Files ExecutableFile
Linker ,___ _ _ _ _ ____ file-name.exe
Format: Binary ._ Format: Binary
LECTURE 2
1-. ALgor-Ltl-1 Vvt:
As stated earlier an algorithm can be defined as a finite sequence of
effect statements to solve a problem. An effective statement is a clear,
unambiguous instruction that can be carried out .Thus an algorithm should
special the action to be executed and the order in which these actions are to
be executed.
ALgorLtvtVvt :pro:perttes:
• Finiteness: the algorithm must terminate a finite number of steps.
• Non-ambiguity: each step must be precisely defined. At the
completion of each step, the nest step should be uniquely determined.
• Effectiveness: the algorithm should solve the problem in a reasonable
amount of time.
Exam pie 2: Devolve an algorithm that allows the user to enter the count of
numbers in a list followed by these numbers. The algorithm should find and
output the minimum and the maximum numbers in the list.
An algorithm for this might be:
• Initialize.
• Get count of numbers.
• Enter numbers and find maximum and minimum.
• Output result.
The user might enter zero for the count. To deal with this case the above
general case can be extended as follows to be an algorithm:
1. Initialize the require variables.
2. Get count of numbers.
3. If count is zero then exit.
4. Otherwise begin.
5. Enter numbers.
6. Find max and min.
7. Output result.
8. End.
2. fLowcl-1 et rts
A flowchart is a graphical representation of an algorithm or of a portion
of an algorithm .Flowcharts are drawn using symbols. The main symbols used
to draw a flowchart are shown in following figure.
Start and Stop Symbols
Connector symbols
Example 1:
Draw a flowchart to read 3 numbers: x, y and z and print the largest
number of them.
Start
Readx
Ready
No
No
Max=z
Print max
Example 2:
Draw the flowchart required to find the sum of negative numbers
among 50 numbers entered by the user.
Start
Counter=O
Sum=O
Read number
Counter=counter+ 1
NO
Sum=sum + number
NO
counter
> 50
Print sum
-- --
WORK SHEET (1)
...._-----------~- --
AN INTRODUCTION
Ql: What do you means by program?
( [ { } ]
) < = > , (Comma)
\\
(Double Conati ons) . (Dot) : (Colon) ; (Semicolon) i....i (Blank Space)
In C++ language, upper case and lower case letters are distinct and hence
there are 52 letters in all. For example bag is different from Bag which is
different from BAG.
2 ,~eV\,ttfters:
An identifier is a name given to some program entity, such as variable,
constant, array, function, structure, or class. An identifier is a sequence of
alphanumeric (alphabetic and numeric) characters, the first of which must be
a letter, and can't contain spaces. The length of an identifier is machine
dependent. C++ allows identifiers of up to 127 characters.
A variable should not begin with a digit. C++ does not set a maximum
length for an identifier. Some examples of valid identifiers are as follows:
My_name (7 char.)
(1 char.)
B (1 char.)
Examples of invalid identifiers are:
3ab a()test ros sal
The keywords are also identifiers but cannot be user defined, since they
are reserved words. All the keywords should be in lower case letters. Reserved
words cannot be used as variable names or constant. The following words are
reserved for use as keywords:
( a) Integer constants: Do not contain decimal points: int x,y; short int x,y;
longint x,y;
► Integer data: size (16 or 32) fill in -2 15 to 2 15- 1 for 16 bit and -231 to
23 1- 1 for 32 bit.
► Short integer: fill in -2 15 to 2 15- 1.
► Long integer: fill in -231 to 23 1- 1.
► Unsigned: fill in (0 to 65635) for 16 bit and (0 to 4,294, 967, 295) for
32 bit.
(b) Floating point constants: Positive or negative numbers are represented
in exponential form. The floating point constant consists of an optionally
(signed) integer or fixed point number (the mantissa) followed by the
letter E and e and an optionally signed integer (the exponent). Ex.
(901 0e 10, 77 .11 E- 11 J.
► Float 4 bytes.
► Double 8 bytes.
► Long double 12 or 16.
( c) Hexadecimal constants: Hexadecimal numbers are integer numbers of
base 16 and their digits are Oto 9 and A to F.
(d)Octal constants: Octal numbers are numbers of base 8 and their digits
are Oto 7.
3. Character Constants: A character represented within single quotes
denotes a character constant, for example 'A', 'a',':','?', etc ...
Its maximum size is 8 bit long, signed, and unsigned char are three distinct
types.
Char x; char x,y,z;
The backslash (\) is used to denote non graphic characters and other
special characters for a specific operations such as:
;; ~;:: : ~;::: ::;;;:: : ~;::: ~;::: ~;:: : ~;::: ::;;;:: : ~;:: ;::~: ;::~: ;:::~ : ;::~: ;::~ : ;::~: ;::~: ;:::~ : ;::~: ;::~ : ;::~: ;::~ : ~? : ;::~: ;::~ : ;::~: ;::~: ;:::~ : ;::~: ;::~ : ;:: . ~;::. ~;::. ~;::. ~;::. ~;::. ~;::. ~;::. ~;:: . ~;::. ~;::. ~;::. ~;::. ~;::. ~;::. ~;::. ~;::. ',,'
//
Comparison and logical Relational,equality,logical /
// /
;~ operators operators /
'
/
» > /
/~;:'.; ~{; ~;:'.; ~;:'.; ~;°; ~;:'.; ~{; ~;:'.; ~;:'.; '- . /,
/ , '. /,
/ , '. /'-. / , ~ /'-.
/ , '. /,-. / , '. /,
/ , '. /,
/ , '. /, / , ~ /'-.
/ , '. /, / , '. /,
/ , '. /,
/ , '. /'-. / , ~ /,
/ , '. /,-. / , '. /,
/ , '. /,
/ , '. /, / , ~ /,
/ , '. /,-. /s. '-/.
/ . 'V/ .. '-/. '-/
..._,. V
. '-/. '-/. '-/ .. '-/.
. ..._,. ' - / . V
'-/ . '-/. '-/. ' / . '-/. '-/ . '-/. '-/. ,)::~
..._,. V . ' V . ' - / . V . ..._,. V . ..._,. ' - / . v.:.·
= Assign right hand side (RHS) value to the left hand side (LHS).
+= Value of LHS var. will be added to the value of RHS and assign it
back to the var. in LHS.
-- Value of RHS var. will be subtracted to the value of LHS and
assign it back to the var. in LHS.
*= Value of LHS var. will be multiplied to the value of RHS and
assiqn it back to the var. in LHS.
/= Value of LHS var. will be divided to the value of RHS and assign
it back to the var. in LHS.
%= The remainder will be stored back to the LHS after integer
division is carried out between the LHS var. and the RHS var.
>>= Right shift and assign to the LHS.
Exercise:
Rewrite the equivalent statements for the following examples, and find it
results. Assume: X=2, Y=3, Z=4, V=l 2, C=8.
Examples:
Example 1:
a=4,b=5,c=6
(a<b)&&(b<c) (a<b) I I (b>c) ! (a<b) I I (c>b) (a<b) I I (b>c) &&(a>b) I I (a>c)
T && T T II T !(TI II T T I I F && F I I F
T T F II T T II F II F
T T II F
T
Example 2:
Assume: X=0, Y=l, Z=l. Find the following expression:
M=++X 11 ++Y&&++Z
M = + +X 11 + +y && ++ z
= l I I (2 && 2)
= T II (T && T)
=T II T
=T
=l
( e) special operators:
1. Unary operator:
~ Bitwise complement.
++ Increment.
-- Decrement.
Type Forced type of conversion
Size of Size of the subsequent data type or type in byte.
Every group of related functions is stored in a separate library called (header file).To use
the cin and cout must include the header file iostream.
~ main(), is the name of C++ function. Every C++ program must have a function called
main.
~ void, is the return type of the main function. When the return type of a function is void,
this function will not passes back any value to the calling function.
Some programmers use int as a return type for the main function, in this case a
retum(O) statement must be written as a last statement of the main function-body.
~ I/,text after these symbols is a comment. It does not affect the program code, and
compilers normally ignore it.
~ cout, the input stream object. It passes the characters quotes (") to the terminal screen.
screen
D
0-@, f ·outputlist'j
Insertion
or Send
Operator
~ cout«"C++ Language"
~ cin, the input stream object. It reads the input values from the keyboard.
cin ( variable )
t Extraction
/ \ or Get from
(.__....,........,.._....,...__ _,} Operator
keyboard
ex: cin>>x;
The endl is used in c++ to represent a new line, as shown in the following
example:
Exam le 2
#include<iostream.h> Out11ut:
void main() hallow
{ students
cout << "hallow" << endl;
cout << "students";
}
The \n is a special escape code, also used in C++ to represent a new line, as
shown in the following example:
Example 3
#include<iostrea m. h> Out11ut:
void main() hallow
{ students
cout << "hallow \n";
cout << "students";
}
A declaration is a process of naming the variables and their statements
datatypes in C++. C++ allows declaration of the variables before and after
executable statements. A variable ia an object that may be take on values of
the specified type.
Also ,a variable is a location in the computer's memory where a value
can be stored for later use by the program. Variables are like buckets that
hold data. These data buckets are really locations in the computer's memory.
variable
name Content Address
X 70 03F
The variable must be declared by specifying the datatype and the identifier.
datatype id.1, id2, .. .,idn;
Example 5
~ The following program reads three different inputs and outputs it.
#include<iostream.h>
void main() Out1111t:
{ input integer number: 5
int n; float f; char c;
input decimal number: 4.2
cout << "input integer number:";
input character: A
cin>>n;
cout<<endl;
cout << "input decimal number:";
cin>>f;
cout<<endl;
cout << "input character:";
cin>>c;
}
4 Go 11\.,Sta 11\.,tS:
Like variables, constants are data storage locations. Unlike variables, and as
the name implies, constants don't change.
const int myage=23;
const double pi=3. l 4;
const float salary=20.5;
Example 6
~ Write a program that reads the radius of a circle, then computes and
outputs its area.
#include<iostrea m. h> Output :
void main()
enter the radius of circle: 5
{
const float pi = 3.14; the area of circle: 78.5
int r; float c;
cout << "enter the radius of circle:";
cin>>r;
cout<<endl;
c = r * r * pi;
cout << ''the area of circle:"<< c;
}
Exam le 7
~ The following program computes the arethmatic operators.
#include<iostream.h>
void main()
{ Output:
int a,b,sum,sub,mul,div; Enter any two numbers
cout << "enter any two numbers<<endl; 10 20
A=l0 b=20 sum=30
cin>> a>>b;
Sub=-10
sum=a+b; Mul=200
sub=a-b; Div=O
mul=a*b;
div=a/b;
cout<<"a="<<a<<"b="<<b<<"sum="<<sum<<endl;
cout<<"sub="<<sub<<endl;
cout<<"mul="<<mul<<endl;
cout<< "div="<< div<< endI;
}
Exam le 8
~ The following program computes different division operators.
#include<iostream.h> Outr)Ut:
void main()
x= 3
{
y= -5
int x, y, z, r ; z= -5
x= 7 I 2; r= 5
cout << "x=" << x <<endl;
y=17/(-3);
cout << "y="<< y <<endl;
z=-17 /3;
cout << "z="<< z <<endl;
r=-17/(-3);
cout << "r="<< r <<endl;
}
The modulus operator "%" is used with integer operands (int, short, long,
unsigned). It can't be used with float or double operands.
Example 9
#include<iostream.h>
void main()
{ Output:
inty1,y2; y1=2
yl = 8 %3; y2=-2
y2 = -17 % 3;
cout << "yl="<< yl <<endl;
cout << "y2="<< y2 <<endl;
}
Lecture 5
Example 1:
Write the following equation as a C++ expression:
a+b+c+d+e
f= 10
Solution:
f = (a + b + c + d + e) / 10;
Note: the parentheses here are required because division has
higher precedence than addition.
Example 2:
State the order of evaluation for the following expression:
Z = P * R % Q + W / X - Y;
Solution: Z = P * R % Q + W / X - Y;
1. *
2. % ,---,
I ~ II 3I 1
3. I
4
4. +
5. - 5
Example 1
~ Write C++ program to perform the above equation:
#i nclude<iostrea m.h>
void main()
{
int Z, P, R, Q, W, X, Y;
cout << "enter P:"; cin >> P;
cout << "enter R:"; cin >> R;
cout << "enter Q:"; cin >> Q;
cout << "enter W:"; cin >> W;
cout << "enter X:"; cin >> X;
cout << "enter Y:"; cin >> Y;
Z= P * R % Q + W / X - Y;
cout << "the result="<< Z;
2 Tue "Vv'.,ettV\.V\" Ltbretrt:1:
The "math.h" library contains the common mathematical function used in the
scientific equations.
vx
Example:
Write the following equation as a C++ expression and state the order of
evaluation of the binary operators:
sin(x) - x5
f= X
ln(x) +
4
Solution:
f = sqrt ((sin(x) - pow(x,5)) / (log(x) + x/4 ))
Order of evaluation:
f = sqrt ({sin{x) - pow{x,5)} I (log(x} + x/4))
I I .___ __, L___J LJ
1 2 3 4
5 6
7
8 I
Exercise:
Write the following equation as a C++ expression and state the order of
evaluation of the binary operators:
2
x y - 3 sin(x)
z=
tan x3 + x3 /y
Solution: ?
The ++ and - - operators can be written either before the variable (prefix
notation) or after the variable (postfix notation) as in the following:
Output: Output:
8 7
8 8
Example 2
~ Write C++ program to convert a base of a number:
#i nclude<iostrea m.h> Enter number
void main() 10
{ Decimal base=lO
int value; Hexadecimal base=a
Octal base=l2
cout << "enter number:"; cin >> value;
cout << "Decimal base="<<dec<<value<<endl;
cout << "Hexadecimal base="<<hex<<value<<endl;
cout << "Octa base="<<oct<<value<<endl;
}
Exam le 3
~ Write C++ program to use tab:
#include<iostrea m.h>
#i nclude<ioma ni p.h>
void main( void) I 200 300
{
int a,b;
a=200;
b=300;
cout<<a<<' \ t'<< b<<endl;
}
Example 4
~ Write C++ program to use setw:
#i nclude<iostrea m.h>
#i nclude<ioma ni p.h>
200 300
void main( void) 200 300
{
int a,b;
a=200;
b=300;
cout<< setw(5)< <a< <setw(5)< <b< <endI;
cout<<setw(6 )<<a<<setw(6)<< b<<endl;
}
-- --
WORK SHEET (2)
.... ......
Q8: What are the main types of variables, its sizes, and its range of
values?
Ql 3: What are the main difference between prefix and postfix notation?
Ql 5: Write C++ program to read x and compute sin, cos, and tan of x.
Ql 7: Given that A and B are real variables with values 1.5, and 2.5
respectively, and C is integer variable with value 3, evaluate the
following: NOT (A< OJ AND (B/C <= OJ.
Ql 9: Write a program to read a set of (5J real no.sand find out the
sum and average of them.
LECTURE 6
Conditional expressions are mainly used for decision making. C++ provides
multiple selection structures: if, if/else, else if, nested if and switch.
statement1
Exam le 2
~ Write a C++ program to read a number and check if it's positive,
if it's so print it, add it to a total, and decrement it by 2:
#include<iostream.h>
void main()
{
int num, total=O;
cin >> num;
if ( num >= 0)
{ cout << num <<" is a positive";
total += num; num = num - 2;
} }
General Form of If/else statement:
if ( expression) if ( expression)
statementl ; { statements }
else statement2 ; else {statements}
In this case, either of the two statements are executed depending upon the
value of the expression. Note that there is a semicolon after each of the
statement but not after the IF expression. Note that the else statement without
braces leads to confusion so:
If (i>j) { If ( a>b)
temp=a;
}
Else
temp=b;
Exam le 3
~ Write a C++ program to read a student degree, and check if it's
degree greater than or equal to 50, then print pass, otherwise print fail:
#i nclude<iostrea m.h>
void main()
{
int degree;
cin >> degree;
if ( degree >= SO )
cout << "pass";
else
cout<< "fail";
}
Exam le 4
~ Write a C++ program to read a number, and check if it's even or
odd:
#i nclude<iostrea m.h>
void main()
{
int num;
cin >> num;
if ( num % 2 == 0)
cout << "even";
else
cout << "odd";
}
5. 6Lse tf st~teV\l\.eV\..ts:
General Form of else if statement:
Example 1:
if (value== 0) cout << "grade is A";
else if (value== 1 ) cout << "grade is B";
else if (value== 2) cout << "grade is C";
else cout << "grade is X";
Exam le 5
~ Write a C++ program to read a number, and print the day of the
week:
#include<iostrea m. h>
void main()
{
int day;
cin >> day;
if ( day == 1 ) cout << "Sunday";
else if (day == 2 ) cout << "Monday";
else if (day == 3 ) cout << "Tuesday";
else if (day== 4) cout << "Wednesday";
else if (day== 5) cout << "Thursday";
else if (day == 6 ) cout << "Friday";
else if (day == 7 ) cout << "Saturday";
else cout << "Invalid day number";
}
Exam le 6
~ Write C++ program to compute the value of Z according to the
following equations:
x+5 :x<O
Z= { cos(x} + 4 : x = 0
✓x :x>O
#i nclude<iostrea m.h>
void main()
{
int Z, x;
cout << "Enter X value \ n";
cin >> x;
if ( x < 0 ) Z= x + 5;
else if ( x == 0 ) Z= cos(x) + 4;
else Z= sqrt(x);
cout << "Z is " << Z;
}
G. Nes.teot rf steitevtA..ell\,ts.:
Some of the samples of NESTED if-else constructions are shown below:
switch ( selector)
{
case labe/1 statementl ; break;
case labe/2 statement2 ; break;
case labe/3 statement3 ; break;
Example 2
~ Write C++ program to read two integer numbers, and read the
operation to perform on these numbers:
#i nclude<iostrea m.h>
void main()
{
int a, b;
char x;
cout << "Enter two numbers \ n";
cin >>a>> b;
switch ( x)
{
case'+': cout <<a+ b;
break;
case '-': cout << a - b;
break;
case '*': cout << a * b;
break;
case '/': cout << a / b;
break;
default: break;
}
}
}
case label-n : statement-n; break;
defa uIt : statement-e ; break;
Example 3
~ Write C++ program to read integer number, and print the name of
the computerized department:
#i nclude<iostrea m.h>
void main()
{
int i,j;
cout << "Enter the number for the department name \n";
cin >> i>>j;
switch (i)
{
case 1: cout << "Software Engineering Department"; break;
case 2: cout << "Control and computers Department"; break;
case 3: cout << "Computer Sciences Department";
cout<<"Enter the no. of branch";
switch(j)
{
case 1: cout << "Software"; break;
case 2: cout << "Information system"; break;
case 3: cout << "Security";
case 4: cout << "Al";
}
default: cout << "Invalid day number"; break;
}
}
Example 4
~ Write C++ program to read integer number, and print if its even or
odd:
#i nclude<iostrea m.h>
void main()
{
int value;
cout << "Enter the number \n";
cin >> value;
cout<<(valueo/o2==0?"even":"odd");
}
I WORK SHEET (3)
Selection Statements
I
Ql: Write C++ program to read two integer numbers then print "multiple"
or "not" if one number is a multiple to another number.
Q2: Write C++ program to read integer number and print the equivalent
string.
e.a:
o ➔ zero
1 ➔ one
2 ➔ Two
Q3: Write C++ program to read a score of student and print the estimation
to refer it.
e.a:
100 - 90 7 Exultant
89 - 80 ➔ Very good
79- 70 ➔ Good
69 - 60 7 Middle
59 - 50 ➔ Accept
49 - 0 ➔ Fail
Q5: Write C++ program to compute the area of circle if the radius r=2.5.
Note: area of circle is r * r *pi,
pi is 3.14
Q6: Write C++ program to read an integer number and check if it is positive
or negative, even or odd, and write a suitable messages in each case.
Q7: Write a program to read 3 numbers, and write the largest and smallest
numbers.
Q8: Write C++ program to read an integer from 1 to 12, and print out the
value of the corresponding month of the year.
Q9: Write C++ program to reads a character and print if it is digit (0 .. 9),
capital letter (A,B, ... ,Z), small letter (a, b, ... ,z), special character ( +, !,
@, #, ~ {, >, ... ).
QlO: Write C++ program to read x and compute the following:
x 2 + 5x - 20
if X > 0
Y ={ o ~ if X = 0
x 2 + (5x) 2 - 10 if x < 0
Ql 2: Write C++ program to read two integer numbers, and read the
operation to perform on these numbers.
Ql 3: Write a program to read X and print Sin X if X>O, square root X f X<O
and absolute X if X/2 is integer.
LECTURE 8
while (condition)
statementl;
while (condition)
{
statementl;
statement2;
statement-n;
}
Statements
Example i = O;
.L while ( i < 10 )
Output:
{
0123456789
cout << i;
i=l 0
i ++;
}
Example i = O;
2: while ( i < 10 )
{ Output: even numbers only
cout << i; 02 4 6 8
i += 2; i=l 0
}
Example i = 1;
3: while ( i < 10 )
{ Output: odd numbers only
cout << i; 13 5 7 9
i += 2; i= 11
}
Exam le 1
~ Write C++ program to find the summation of the following series:
sum= 1 + 3 + 5 + 7 + ... + 99
/in other words: find the summation of the odd numbers, between 0 and lOO)
#i nclude<iostrea m.h>
void main()
{
int count= 1;
int sum= O;
while ( count<= 99 )
{
sum = sum + count;
count= count+ 2;
}
cout << "sum is:"<< sum<< endl;
}
Exam le 2
~ Write C++ program to find the cub of a number, while it is positive:
#i nclude<iostrea m.h>
void main()
{
int num, cubenum;
cout << "Enter positive number \n";
cin >> num;
while ( num > 0)
{
cubenum = num * num * num;
cout << "cube number is:"<< cubenum << endl;
cin >> num;
}
Example 3
~ Write C++ program to find the summation of the following series:
n
[ i2 = 12 + 22 + 32 + I I I + n2
i=l
#i nclude<iostrea m.h>
void main()
{
int i = 1, n ,sum = O;
cout << "enter positive number";
cin >> n;
while ( i <= n )
{
sum+= i * i;
i++;
}
cout << "sum is:"<< sum<< endl;
}
Exam le 4
~ Write C++ program to find the summation of student's marks, and
it's average, assume the student have 8 marks:
#i nclude<iostrea m.h>
void main()
{
int mark, i, sum= O;
float av= O;
i = 1;
while ( i <=8)
{
cout << "enter mark: ";
cin >> mark;
sum = sum + mark;
i++;
}
cout << "sum is:"<< sum<< endl;
av= sum/ 8;
cout << "average is: " << av;
}
Example 5
~ Write C++ program that display the following board pattern:
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
#i nclude<iostrea m.h>
void main()
{
int row= 8, column;
while (row--> 0)
{
column= 8;
if ( row % 2 == 0 )
cout << " ";
while (column--> 0)
cout << "*"·t
cout << '\ n';
}
}
Example 6
~ Write C++ program to check for a line feed and tab of a given
character:
#i nclude<iostrea m.h>
void main()
{
Char ch;
Cout<<"enter a line \n";
Ch=ci n.get();
While (ch!='\n' && ch!='\t')
{ cout.put( ch);
Ch=cin.get(); }
}
General Form of Do/ While statement:
do
statementl ;
while (condition);
do
{
statementl;
statement2;
statement-n;
}
while (condition);
Statements
Example 1: i = O;
do Output:
{
0123456789
cout << i;
i=l 0
i ++;
}
while ( i < 10 )
Example 2: i = O;
do
{ O utput: even numbers only
cout << i; 02 4 6 8
i += 2; i=l 0
}
while ( i < 10 )
Example 7
~ Write C++ program to valid input checking, that accept the
numbers between 50 ... 70 only:
#include<iostream.h>
void main()
{
int accept= 1;
int x, low= SO, high= 70;
do
{
cout << "enter number: ";
cin >> x;
if ( x >= low && x <= high )
accept =1;
else
accept= O;
Exam le 8
~ Write C++ program to find the summation of student's marks, and
it's average, assume the student have 8 marks:
#i nclude<iostrea m.h>
void main()
{
int mark, i, sum= O;
float av= O;
i = 1;
do
{
cout << "enter mark: ";
cin >> mark;
sum = sum + mark;
i++;
}
while ( i <=8)
cout << "sum is:"<< sum<< endl;
av= sum/ 8;
cout << "average is: " << av;
}
Example 9
~ Write C++ program to find the factorial of n:
n ! = n * n- 1 * n-2 * n-3 * . . . * 2 * 1
#i nclude<iostrea m.h>
void main()
{
int n, f = 1;
cout << "enter positive number:";
cin >> n;
do
{
f = f * n;
n --;
}
while ( n > 1 );
cout << "fadorial is: "<< f;
}
Example 10
~ Write C++ program to find the summation of even numbers
#i nclude<iostrea m.h>
void main()
{
int max,sum,digit;
digit=2;
cout << "enter a number: ";
cin >> max;
sum=O;
do
{
Sum=sum+digit;
Digit+=2;
}
while ( digit<=max );
cout << "2+4+ ...="<<max<<"sum="<<sum<<endl; }
LECTURE 9
1. for stateVIA-eV'vt:
General Form of For statement:
Example 1
~ Write C++ program to add the numbers between 1 and 100:
#i nclude<iostrea m.h>
void main( )
{
int sum= O;
for ( int i = 1; i <= 100; i ++ )
sum= sum+ i;
cout << "sum is:"<< sum;
}
Example 2
~ Write C++ program to find the factorial of n (usivtg forstatew,e0,t):
n ! = n * n-1 * n-2 * n-3 * . . . * 2 * 1
#i nclude<iostrea m.h>
void main()
{
int n, f = 1;
cout << "enter positive number:";
cin >> n;
for ( inti = 2; i <= n: i ++ ) .. 111
1 for ( int i = n: i > 2; i -- )
f = f * i;
cout << "fadorial is: "<< f;
}
Example 3
~ Write C++ program to the result of the following:
20
L af
i= l
#i nclude<iostrea m.h>
void main()
{
int sum= 0;
for ( inti = 1: i <= 20; i ++ )
sum = sum + ( i * i ):
cout << "The sum is: "<< sum;
}
Example 4
~ Write C++ program to read 10 integer numbers, and find the sum
of positive number only:
#i nclude<iostrea m.h>
void main()
{
int num, sum= 0;
for (inti= 1; i <= 10; i ++)
{
cout << "enter your number: ";
cin >> num:
if ( num > 0) sum= sum+ num;
}
cout << "The sum is: "<< sum;
}
Example 5
~ Write C++ program to print the following series: 1, 2, 4, 8, 16, 32, 64
#i nclude<iostrea m.h>
void main()
{
int x;
for ( X = 1; X < 65; X *= 2 )
cout << x <<" ";
}
Exam le 6
~ Write C++ program to print the following:
#i nclude<iostrea m.h> 1 10
void main() 2 9
{ 3 8
int x; 4 7
for ( X = 1; X < 7; ++ X ) 5 6
cout << x <<"\ t" << 11 - x << end I; 6 5
}
Example 7
~ Write C++ program to read a line using for loop
#include<iostrea m.h>
void main()
{
Char ch;
cout << "Enter a line\ n";
for (;( ch=ci n.get())!=' \ n';) {
cout<<"Your charader is:"<<endl;
cout.put( ch);
}
}
0 We can use more than one control with for statement, as follow:
for ( int m = 1, int n = 8 ; m < n; m ++ , n -- )
I
i= l
I
10 AAAAA
12345678910 12345678910 12345678910 12345678910 12345678910
j= l
#i nclude<iostrea m.h>
void main()
{
inti, j, sum= O;
for ( i = 1; i <= 5; i ++ )
for ( j = 1; j <= 10; j ++)
sum= sum+ ( i + 2 * j );
cout << "sum is:"<< sum;
}
Example 9
~ Write C++ program to print the following figure:
+ +
+ + +
+ + + +
+ + + + +
+ + + + + +
+ + + + + + +
+ + + + + + + +
+ + + + + + + + +
+ + + + + + + + + +
#i nclude<iostrea m.h>
void main()
{
inti, j;
for ( i = 1; i <= 10; i ++ )
{
for ( j = 1; j <= i; j ++ )
cout << "+ ";
cout << "\n";
}
}
Exam lel0
~ Write C++ program to read a line using for loop
#i nclude<iostrea m.h>
void main()
{
cout << "Explaining the nested for loop\n";
for (int i=0;i<=2;i++) {
cout<<i;
for (int k=0;k<=2;k++) {
cout<<"computer sciences department \n";
} } }
Exercise:
What is the output of the following C++ program?
#include<iostrea m. h>
void main()
{
int i, j, k;
for ( i = 1; i <= 2; i ++ )
{
for ( j = 1; j <= 3; j ++ )
{
for ( k = 1; k <= 4; k ++ )
cout << " + ";
cout<< "\n";
}
cout<< "\n";
}
}
LECTURE 10
(b)
The continue is used to repeat the same operations once again even it it
checks the error. Its general syntax is: ( continue;)
It is used for the inverse operation of the break statement. The following
program segment will process only the positive integers. Whenever a zero or
negative value is encountered, the computer will display the message "zero
or negative value found" as an error and it continues the same loop as long
as the given condition is satisfied.
Cin>>value;
While (value <=100) {
If (value <=0)
Cout<<"zero or negative value found\n";
Continue;
} }
Example 1: Example 2:
do
{ n = 1;
cin >> x; for ( i = 1; i < 5; ++i )
cin >> n; {
if ( n < 1 ) continue; cin >> x;
cout << x; n = 5 * x++ * ( - 1) / n;
-- n; if ( n < 1 ) continue;
} cout << n;
while ( n < 1 ); }
( c) c;oto SteiteV\A.evivt:
Exam le 2
~ Write C++ program to check if zero or negative value found:
#i nclude<iostrea m.h>
void main( )
{
Start: cout<<"***\n";
Goto start;
}
2. Conditional Goto: ltis used to transfer the control of the execution from
one part of the program to the other in certian conditional cases.
Example 2
~ Write C++ program to check if zero or negative value found:
#i nclude<iostrea m.h>
void main( )
{
Int value,i=O;
While i<=lO) {
Cout<<"enter a number \n";
Cin>>value;
Cout<<"zero or negative value found \n";
Goto error;
}
Error:
Cout<<"input data error \ n";
}
20
~ a~
1
Q3: To find the result of the following: i=1 •
Q4: Read 10 numbers/ and find the sum of the positive numbers only.
Q7: Find the sum and average of the 8 degrees of the student.
for(i=l;i<=8;i++) i=l; i=l;
{ while ( i<=8) do
cin >> d; { {
s = s + d; cin > > d; cin >> d;
} s = s + d; s = s + d;
av= s / 8; i++; i++;
} }
av= s / 8; while ( i< =8);
av= s / 8;
QB: Rnd the cub of n numbers/ while the entered number is a positive.
cin >> x; do
while ( x > 0 ) {
Cant be solve this problem { cin >> x;
using For statement C = X * X * x; C = X * X * x;
cin >> x; }
} while ( x > O);
lwoRK SHEET (4)1
Iteration Statements
Using While Statement:
Ql: Write C++ program to find the summation of the odd numbers,
between 0 and 100.
Q4: Write C++ program to display the first 100 odd numbers.
Q6: What are the output of the following segment of C++ code:
int count= 1;
do
{
cout << (count% 2? "****" : "+++++") << endl;
++ count;
}
while (count<= 10 );
Q7: Write C++ program that utilize looping and the escape sequence \t to
print the following table of value:
N 10 * N 100 * N 1000 * N
1 1....1 1....11....11....11....11....1 10 100 1000
2 20 200 2000
3 30 300 3000
4 40 400 4000
Hint\t to print six spaces.
+ + + + + + + + + +
+ + + + + + + + +
+ + + + + + + +
+ + + + + + +
+ + + + + +
+ + + + +
+ + + +
+ + +
+ +
+
Ql 5: Write C++ program to read 10 marks, suppose the student pass if all
marks greater than or equal 50, and the average greater than or
equal 50. If student fails in some lessons then print the number of these
lessons, if student fails in average then print "fail in average".