0% found this document useful (0 votes)
4 views

1fp2023

Uploaded by

alfaseehyf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

1fp2023

Uploaded by

alfaseehyf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

‫‪st‬‬

‫‪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

Computer is a device capable of performing computations and making


logical decisions at speeds millions and even billions of times faster than
human beings.

Computers process data under the control of sets of instructions called


computer programs.

Programming is the process of writing instructions for a computer in a certain


order to solve a problem.

The computer programs that run on a computer are referred to as software


(SW). While the hard component of it is called hardware (HW).
Developing new software requires written lists of instructions for a computer to
execute. Programmers rarely write in the langauage directly understood by a
computer.

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

For the last couple of decades, the C programming language has


been widely accepted for all applications, and is perhaps the most powerful
of structured programming languages. Now, C++ has the status of a
structured programming language with object oriented programming (OOP).
C++ has become quite popular due to the following reasons:
1. It supports all features of both structured programming and OOP.
2. C++ focuses on function and class templates for handling data
types.

4. c + + Prog rct VIA, DeveLo:p VlA-eV\.,t Process (PDP) :


C++ programs typically go through six phases before they can be
executed. These phases are:
1. Edit: The programmer types a C++ source program, and makes
correction, if necessary. Then file is stored in disk with extension (.cpp).
2. Pre-Processor: Pre-processing is accomplished by the pre-proceccor
before compilation, which includes some substitution of files and other
directories to be include with the source file.
3. Compilation: Converting the source program into object-code.
4. Linking: A linker combines the original code with library functions to
produce an executable code.
5. Loading: The loader loads the program from the disk into memory.
6. CPU: Executes the program, residing in memory.
These steps are introduced in the figure below:
q Source File
1----------il
Format: Text
file-name.cpp

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.

Example 1: Develop an algorithm that inputs a series of number and output


their average .
A computer algorithm can only carry out simple instruction like:
• "Read a number".
• "Add a number to anther number''.
• "Output a number''.
Thus an algorithm is:
1. Carry out initialization required.
2. Read first number.
3. While the number of numbers is not complete do
4. begin
5. Add the number to the accumulated sum.
6. increment the count of numbers entered.
7. Read next number.
8. End
9. Evaluate the average.

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

Input and Output Symbols

Mathematical and logical


processing symbol

Decision making symbol

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?

Q2: Why C++ language becomes quite popular?

Q3: Talk briefly about C++ program development process?

Q4: Write an algorithm and flowcharts for the following:

a. Sum the even numbers for n numbers.


b. Display numbersfrom Oto 10.
c. The multiplication of 10 numbers.
Lecture 3
1. Gvta racter set:
C++ has the letters and digits, as show below:
Uppercase: A, B, c, ... , z
Lowercase: a, b, c, ... , z
Digits: o, 1, 2, ... ,9

Special Characters: All characters other than listed treated as special


characters for example:
+ * I A

( [ { } ]
) < = > , (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:

Some of C++ Language Reserved Words:


break case char Cln cout
delete double else enum false
float for goto if int
lonq main private public short
sizeof switch true union void

There are three types of constants: string constants, numeric constants,


and character constants.

1. String Constants: A string constants are a sequence of alphanumeric


characters enclosed in double quotation marks whose maximum length is 255
characters. In the following are examples of valid string constants: ("The
result=", "RS 2000.00", "This is test program"}. The invalid string constants are
like: (Race, "My name, 'this'}.
2. Numeric Constants: Numeric constants are positive or negative numbers.
There are four types of numeric constants: integer, floating point,
hexadecimal, and octal.
Integer Integer
Short integer (short)
LonQ inteQer (lonQ)
Float Single precision (float)
Double precision (double)
LonQ double
Hexa Short hexadecimal
LonQ hexadecimal
Unsigned char
Unsigned integer
Unsigned
Unsigned short integer
UnsiQned lonQ inteQer
Octal Short octal
LonQ octal

( 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:

Special Escape Code:


Escape Code Description
New line. Position the screen cursor to the beginning of the next
\n
line.
Horizontal TAB (six spaces). Move the screen cursor to the next tab
\t
stop.
Carriage return. Position the cursor to the beginning of the current
\r
line, do not advance to the next line.
\a Alert. Produces the sound of the svstem bell.
\b Backspace
\\ Backslash. Prints a backslash character.
\f Form feed
\v Vertical tab
\" Double quote. Prints a (") character.
\o Null character
\? question mark
\ooo Octal value
\xhhh Hexadecimal value
5. c+ + o:perettors:

;; ~;:: : ~;::: ::;;;:: : ~;::: ~;::: ~;:: : ~;::: ::;;;:: : ~;:: ;::~: ;::~: ;:::~ : ;::~: ;::~ : ;::~: ;::~: ;:::~ : ;::~: ;::~ : ;::~: ;::~ : ~? : ;::~: ;::~ : ;::~: ;::~: ;:::~ : ;::~: ;::~ : ;:: . ~;::. ~;::. ~;::. ~;::. ~;::. ~;::. ~;::. ~;:: . ~;::. ~;::. ~;::. ~;::. ~;::. ~;::. ~;::. ~;::. ',,'

" Arithmetic operators '


" '
'
Assignment operators <
//
<
C++
//

//
Comparison and logical Relational,equality,logical /

// /

;~ operators operators /

'
/

Bit wise logical operators '/


"
'
//

Special operators Unary, ternary, comma <


/

» > /

ll Scope, new&delete, other / /

/~;:'.; ~{; ~;:'.; ~;:'.; ~;°; ~;:'.; ~{; ~;:'.; ~;:'.; '- . /,
/ , '. /,
/ , '. /'-. / , ~ /'-.
/ , '. /,-. / , '. /,
/ , '. /,
/ , '. /, / , ~ /'-.
/ , '. /, / , '. /,
/ , '. /,
/ , '. /'-. / , ~ /,
/ , '. /,-. / , '. /,
/ , '. /,
/ , '. /, / , ~ /,
/ , '. /,-. /s. '-/.
/ . 'V/ .. '-/. '-/
..._,. V
. '-/. '-/. '-/ .. '-/.
. ..._,. ' - / . V
'-/ . '-/. '-/. ' / . '-/. '-/ . '-/. '-/. ,)::~
..._,. V . ' V . ' - / . V . ..._,. V . ..._,. ' - / . v.:.·

L. Arithmetic operators: These operators require two variables to be


evaluated:
+ addition - subtraction * multiplication
/ division % modulo (remainder of an integer division)

The division result are:


Integer/ integer= integer ► 39/7=5
Integer/ float = float ► 39 /7 .0 =5.57
float / integer = float ► 39 .0/7 =5.57
float / float = float ► 39.0/7.0=5.57
while 39%5=7, since 39=7*5+4
Arithmetic operators as per precedence:
( ) for grouping the variables.
- Unary for negative number.
* I multiplication & division.
+ - addition and subtraction.
Example: X+y*X-Z, where X=5, Y=6, and Z=8.

5 + {6*5)-8 -+ {5+30)-8 -+ 35-8-+ 27

2. Assignment Operators: The operatonal assignment operator has the


form:
Variable= variable operator expression;
Ex: x=x+5; y=y*l O;
The operational assignment operator can be written in the following
form:
Variable operator = expression
Ex: x+=5; y*= 1O;
It is used to assign back to a variable, a modified value of the present
holding:

= 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.

<<= Left shift and assign to the LHS.

&= Bitwise AND operation and assign to LHS

1= Bitwise OR operation and assign to LHS

~= Bitwise complement operation and assign to LHS


This is a valid statements:
A=b=c+4;
C=3*(d=l 2.0/xJ;

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.

Example Equivalent Statement Result


X += 5 X=X+5 X f- 7
Y-= 8 Y = Y- 8 y f- -5
Z *= 5 Z=Z*5 z f-
V /= 4 V f-
C%= 3 Cf-

3. Comparision and logical operators: It has three types relational


operators, equality operators, and logical operators.
( a) Relational operators:< less than,> greater than,<= less than or equal,
>= greater than or equal, an expression that use relational operators
return the value of one if the relational is TRUE ZERO otherwise.
Ex: 3 > 4----+ false, 6 <=2 --+false, 10>-32----+ true, (23*7)>= (-67+89) ----+ true
(b) Equality operators:== equal to,!= not equal to
Ex: a=4, b=6, c=8. A==b----+false, (a*bJ !=c----+true, 's' == 'y' --+false.
( c) Logical operators: The logical expression is constructed from relational
expressions by the use of the logical operators not(!), and(&&), or( I I J.

AND(&&) Table: AND(&&) Table:


A B A&&B A B A &&B
T T T 1 1 1
T F F 1 0 0
F T F 0 1 0
F F F 0 0 0
OR ( I I) Table: OR ( I I) Table:
A B A 11 B A B A 11 B
T T T 1 1 1
T F T 1 0 1
F T T 0 1 1
F F F 0 0 0

NOT(!) Table: NOT (!) Table:


A IA A IA
T F 1 0
F T 0 1

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

( d) Bitwise logical operator:


& bitwise AND, A bitwise exclusive OR (XOR), I bitwise inclusive OR,
>> bitwise left shift,<< bitwise right shift,~ bitwise complement.
Ex: x=23 (0001 0111) ~x=132 (1110 1000)
X=33 (0010 0001)
X << 3
0 01000010
0 10000100
00001000 the resultant bit pattern will be (0000 1000)
X=5,y=2 -+ x&y (0000), xly (0111), xAy (0111)

( e) special operators:
1. Unary operator:

* Contents of the storage field to which a pointer is pointing.


& Address of a variable.

- Negative value (minus sign).


! Negative (0, if value f:. 0, 1 if value =O).

~ Bitwise complement.
++ Increment.

-- Decrement.
Type Forced type of conversion
Size of Size of the subsequent data type or type in byte.

2. Ternary operator: It is called conditional operator, it is like if else


construction:
Expression 1 ? expression 2 expression 3
If (v%2 == 0)
e = true
E= (v%2 ==OJ? True : false
Else
e=false
3. Comma operator:(,)
Int a,b,c; or it is used in control statements
4. Scope operator:(::) It is used in a class member function definition.
5. New and delete operators: it is a method for carrying out memory
allocations and deallocations.
6. Other operators: parentheses for grouping expressions, membership
operators.

Some variables are declared as integers but sometimes it may be


required to bet the result as floating point numbers. It is carried out in two
ways:
(A) Converting by assignment: (B) Cast operator:
int x; floaty; x=y; Result =(int) (19.2/4); or
Result= int (19 .2/4);
Lecture 4
1. stateVl,1.,ell\,t£:
A statement in a computer carries out some action. There are three
types of statements used in C++; they are expression statement, compound
statement and control statement.
Expression statement Compound statement Control statement
x=y; { If (a>b) {
sum=x+y; a=b+c; a=I;
x=x*x; k=a+l;
y=a+x; }
}

2 c;etttll\,g sta rte~ wttltt c + + :


The skeleton of a typical C++ program structure is given below:
Program heading
Begin
Type or variable declaration
Statements of operation
Results
end

The keyboard and screen 1/0 instructions in C++ are:


(a): COUT/ display an object onto the video screen:
Cout<<var.1 <<var2<< ...<<var.n;
(b): Cin/ It is used to read an object from a standard input device (keyboard):
Cin>>var.1 >>var.2>> ...>>var.n;
To begin learning C++ lets examine our first C++ Program:
Exam le 1
#include<iostream.h> Output:
void main()
Welcome
{
// A program to print welcome
cout << "Welcome";
}

~ #include<iostream.h> this line is for pre-processor directive. Any begins with # is


processed before the program is compiled. C++ programs must be start with #include.

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.

~ {, introducing the statements that define the function.

~ }, indicates the end of the statements in the function.

~ 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 stream insertion operator (or send operator).


~ > >, the stream extraction operator (or get from operator).
~ ; , semicolon, the terminator of every C++ statement.

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;

A variable defined by stating its type, followed by one or more spaces,


followed by the one or more variable names separated by commas, then
followed by semicolon. For example:

unsigned short Int X;


float Y;
char A, a, c;

Note: C++ does distinguish between above A and a variables


(C++ is case-sensitive).
Example 4
~ The following program reads three different inputs and outputs it.
#include<iostream.h>
void main()
{ Output:
int num=3; Number=3
cout << "number="<<num<<"\n";
Character=a
char ch='a';
cout << "character="<<ch<<"\n"; Real number=34.45
float fa=-34.45;
cout<<"real number="<<fa<<"\ n";
}

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.

Common function from math.h library:

Mathematical Expression C++ Expression

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:

Prefix notation: ++ X X is incremented before its value is


taken or returned to current statement.
Postfix notation: X ++ X is incremented after its value is taken
or returned to current statement.

The difference between the Prefix and Postfix notations:


Prefix notation Postfix notation
int y; int y;
int X = 7·f intx = 7· f

cout<< ++x <<endl; cout<< x++ <<endl;


y=x; y=x;
cout<<y; cout<<y;

Output: Output:
8 7
8 8

.3 Met V\,L:puLcttor fuV\,cttoV\,s:


They are special stream functions that change certain characteristics of the
input and output.
(a) Endl: Generate a carriage return or line feed character.
Cout < < "a" < < end I·
f

(b)Setbase: It is used to convert the base of one numeric value into a


nother base
Dec(base 10), hex(base 16), oct(base 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;
}

When using setbase the statement will be:


Cout<<"Decimal base="<<setbase (1 0);
Co ut< <value<<en di;

(c) Setw: It is used to specify the minimum number of character positions on

the O/P field a variable will consume: setw(int w)

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;

(d)Setfill: It is used to specify a different character to fill the unused field

width of the value. Setfill( char f)


Exam le 5
~ Write C++ program to use setfill:
#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;
setfill('"'');
cout<< setw(5)< <a< <setw(5)< <b< <endI;
cout<<setw(6 )<<a<<setw(6)<< b<<endl;

(e)Setfill: It is used to control the number of digits of an output stream


display of a floating point value. Setprecision (int p)
Exam le 6
~ Write C++ program to use setprecision:
#include<iostream.h>
#include<iomanip.h> 1.7
void main( void) 1.66667
{
float a,b,c;
a=5·, b=3·, c=a/b·,
setfill('"'');
cout<<setprecision(l )<<c<< end I;
cout<<setprecision(5)<<c<< endl;

}
-- --
WORK SHEET (2)
.... ......

First Elements of C++


Ql: What do you means by C++ character set?

Q2: What do you means by identifiers? What is the maximum length of


identifiers?

Q3: What do you means by case-sensitive?

Q4: What do you means by reserved word?

Q5: Write a general layout of C++ program. Comment on each part of


it.

Q6: What is the main purpose of endl and \n?

Q7: List and comments on the special escape codes.

Q8: What are the main types of variables, its sizes, and its range of
values?

Q9: What do you means by constants?

Ql 0: List the priorities of the arithmetic operations.

Ql 1: Find the value of A for the following:


A = (5 + 2 * 3 + ( ( 3 - 2 ) * 7) + -9 ) / 2.

Ql 2: What are the main keywords are includes in iostream.h and


math.h?

Ql 3: What are the main difference between prefix and postfix notation?

Ql 4: Find the value of B (true or false) for the following:


i= 5;
j = 9;
B= ! (( i > 0 J && ( i >= j JJ;

Ql 5: Write C++ program to read x and compute sin, cos, and tan of x.

016: Rewrite the equivalent statements for the following examples,


and find it results. Assume: X=2 , Y=3, Z=4, V= 12, C=8.
(X+=5, Y-=8, Z*=5, V/=4, C %=3)

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 8: Write a program in C++ to find the area of a circle.

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.

2. Tvie S~V\-gLe rf StlitteVvteV\-t stnA.cture:


The IF statement is used to express conditional expression. If the given
condition is true then it will execute the statements; otherwise it will execute
the optional statements.

General Form of single-selection If statement:

if ( expression or condition ) statementl ;

statement1

Example 1: if ( avrg >= 3.5 )


cout << "good";

Example 2: if ( X > 0.0)


sum+= x;

Example 3: cin >> num;


if ( num == 0)
zcount = zcount + 1;
Exam le 1
~ Write a C++ program to read any two numbers and
print the largest value of it:
#incl ude<iostrea m.h>
void main()
{
Float x,y;
Cout<<"Enter any two numbers\n";
Cin>>x>>y;
If (x>y)
Cout << "largest value is"<<x<<endl;
}

3. Tvie sL111.,gLe "B-Locts, 1f Sttittell¾e111.,t structure :


The block IF statement are enclosed in ({) and (}) to group declaration and
statements into a compound statement or a block. These blocks are always
considered as a single statement. The structure is:

General Form of single block selection If statement:


if ( expression or condition )
{
statementl ;
statement2;
statement3;
}

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}

4. Tue 1f!eL£e StCite~eV\,t structure:


The IF structure is

true alse .----------,


Statement1 Statement2

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;

Example 1: cin >> value;


if (value>= 0)
cout << "positive";
else
cout << "negative";
Example 2: cin >> numl >> num2;
if ( numl > num2)
cout << num 1;
else
cout << num2;

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:

if ( expression or condition 1 ) statementl ;


else if ( expression or condition 2 ) statement2 ;
else if ( expression or condition 3) statement3;

else if ( expression or condition n ) statement-n ;


else statement-e ;

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:

If (exp.) {Statements} If (exp.) { If (exp.) {


Else { Statements} If (exp.) {Statements} If (exp.) {Statements}
Else { Statements} } Else { Statements} }
Else {Statements} Else {If (exp)
{Statements}
Else {Statement}
}
Exam le 7
~ Write C++ program to find a largest value among three numbers:
#i nclude<iostrea m.h>
void main()
{
#i nclude<iostrea m.h>
void main()
{
Float x,y,r,
Cout<<"Enter any two numbers\n";
Cin>>x>>y,r,
If (x>y) {
If (x>z)
Cout << "largest value is"<<x<<endl;
Else
Cout << "largest value is"<<z<<endl;
}
Else If (y>z)
Cout << "largest value is"<<y<<endl;
Else
Cout << "largest value is"<<z<<endl;
}
LECTURE 7

1.. TVte swttcl-1 selecttoll\, stateV1A.ell\,t (selector):


The switch statement is a special multi way decision maker that tests
whether an expression matches one of the number of constant values,
and braces accordingly.

General Form of Switch Selection statement:

switch ( selector)
{
case labe/1 statementl ; break;
case labe/2 statement2 ; break;
case labe/3 statement3 ; break;

case !abel-n : statement-n ; break;


default : statement-e; break;
}

Example 1: switch (value)


{
case 0: cout << "grade is A";
break;
case 1: coucout << "grade is B";
break;
case 2: coucout << "grade is C";
break;
default: cout << "grade is X";
break;
Exam le 1
~ Write C++ program to read integer number, and print the name of
the day in a week:
#i nclude<iostrea m.h>
void main()
{
int day;
cout << "Enter the number of the day \n";
cin >> day;
switch (day)
{
case 1: cout << "Sunday"; break;
case 2: cout << "Monday"; break;
case 3: cout << "Tuesday"; break;
case 4: cout << "Wednesday"; break;
case 5: cout << "Thursday"; break;
case 6: cout << "Friday"; break;
case 7: cout << "Saturday"; break;
default: cout << "Invalid day number"; 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;

cout << "+ for addition \ n";


cout << "- for subtraction \n";
cout << "* for multiplication \n";
cout << "/ for division \n";
cout << "enter your choice \ n";
cin >> x;

switch ( x)
{
case'+': cout <<a+ b;
break;
case '-': cout << a - b;
break;
case '*': cout << a * b;
break;
case '/': cout << a / b;
break;
default: break;
}
}

2. Nesteol swttcvi seLecttoV\., StCltel/1.A.,eV\.,t:


General Form of Nested Switch Selection statement:
switch ( selector1 )
{
case labe/1 statementl; break;
case labe/2 statement2; break;
case labe/3 switch ( selector2)
{
case labe/1 statementl ; break;
case labe/2 statement2; 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;
}
}

General Form of Conditional statement:

( condition? True False)

Example 1: cin >> value;


cout << (value>= 0? "positive" : "negative"};

Example 2: cin >> X >> y;


cout << ( x < y ? -1 : (x == y ? 0 : 1} };

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

Q4: Write C++ program to represent a simple nested case (selector).

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 1: Write C++ program to read 5 numbers and determine if the numbers


sorted ascending or not.

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

1.. Loo:p statew.,el/\,ts:


The loop statements are essential to construct systematic block styled
programming. C++ provides three iteration structures: while, do/while, and for.

2. wvitLe :&e:pettttol/\, structure:


General Form of While statement:

while (condition)
statementl;

while (condition)
{
statementl;
statement2;

statement-n;
}

Statements

The condition represents the value of a variable, unary or binary expression,


and a value returned by a function.

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:

for ( initialization ; continuation condition ; update )


statementl ;

for ( initialization ; continuation condition ; update )


{
statementl ;
statement2 ;

Example 1: for ( i= 0; i< 10; i++) Output:


cout << i; 0 1 2 3 4 5 6 7 8 9

Example 2: for ( i = 0; i < 10; i + = 2 ) Output: even numbers only


cout << i; 0 2 4 6 8

Example 3: for ( i = 1; i < 10; i + = 2 ) Output: odd numbers only


cout << i; 1 3 5 7 9

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);
}
}

2. More C{bout for sttAteVvtell\,t:

0 We can use more than one control with for statement, as follow:
for ( int m = 1, int n = 8 ; m < n; m ++ , n -- )

0 We can create infinite loop, as follow:


for ( ; ; )
3. Nesteol Loo:ps:
We can put loops one inside another to solve a certain programming
problems. Loops may be nested as follows:
loopl loopl . - - - - loopl
kmp2 [ ~op2
[E::::
['~ro
Exam le 8
~ Write C++ program to evaluate the following series:
5 10
I I
i=l j=l
i +2j

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

1.. 'B. rea rs,tV\,g co V\,trol StClte w.,e V\,ts:


For effective handling of the loop statements, C== allows the use of the
following types of control break statements:

(e1) "E-re~ R, coV\,troL st~teV\ll.eV\,t:


The break statement is used to terminate the control from the loop
statements of the case-switch structure. The break statement is normally used
in the switch-case loop and in each case condition; the break statement
must be used. If not, the control will be transferred to the subsequent case
condition also. The general format of the break statement is: (Break;)

Example 1: for ( i = 1; i < 100; i ++ J


Output:
{
12345678910
cout << i;
if (i== 10) break;
}

Example 2: for ( i = 1; i < 10; + + i J


for ( j = 1; j < 20; ++ j J
{
cout << i * j << endl;
if ( j = = 10 J brea k;

Example 3: Switch (day) {


Case '1 ':cout<<" Monday\n";
Break;
Case '2':
}
Example 1
~ Write C++ program to check if zero or negative value found:
#i nclude<iostrea m.h>
void main( )
{
int value,i;
i=0;
while (i<=l0) {
cout<<"enter a number \n";
cin>>value;
if (value<=0) {
cout<<"Zero or negative value found \n";
brek;
}
i++
}
}

(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:

The goto statement is used to alter the program execution sequence


by transferring the control to some other part of the program. Its general
syntax is: (goto label;)
There are two ways of using this statement:
1. Unconditional Goto: ltis used just to transfer the control from one part of
the programto the other part without checking any condition. It is
difficult in use.

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";
}

Usin For Statement Usin While Statement ile Statement


Q1: Rnd the summation of the numbers between 1 and 100.
for( i=l; i<=lO0; i++) i = 1; i = 1;
s = s + i; while ( i <= 100) do
{ {
s = s + i; s = s + i;
i++; i++;
} }
while ( i <= 100 );

Q2: Rnd the factorial of n.


cin >> n; cin >> n; cin >> n;
for( i=2; i<=n; i++) i = 2; i = 2;
f = f * i; while ( i <= n) do
{ {
f = f * i; f = f * i;
i++; i++;
} }
while ( i <= n);

20
~ a~
1
Q3: To find the result of the following: i=1 •

for( i=l; i<=20; i++) i = 1; i = 1;


s = s + (i *i); while ( i <= 20) do
{ {
s = s + (i *i); s = s+ (i *i);
i++; i++;
} }
while ( i <= 20);

Q4: Read 10 numbers/ and find the sum of the positive numbers only.

for( i=l; i<=lO; i++) i = 1; i = 1;


{ while ( i <= 10) do
cin >> x; { {
if ( x>0 ) s = s + x; cin >> x; cin >> x;
} if(x>0) s=s+x; if ( x>0 ) s = s + x;
i++; i++;
} }
while ( i <= 10);
QS: Represent the following series: 1/ 2/ 4/ ~ 16/ 32/ 64.

for( i=l; i<65; i*=2) i = 1; i = 1;


cout<<i; while ( i<65) do
{ {
cout << i; cout << i;
i*=2; i*=2;
} }
while ( i<65);

Q6: Rnd the sum of the followings = 1 + 3 + 5 + 7 + ... + 99.


for( i=l; i<=99; i+=2) i = 1; i = 1;
s = s + i; while ( i<=99) do
{ {
s = s + i; s = s + i;
i+=2; i+=2;
} }
while ( i< =99);

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.

Q2: Write C++ program to inverse an integer number.


For example: 765432 ➔ 234567

Q3: Write C++ program to find G.C.D between m & n.

Q4: Write C++ program to display the first 100 odd numbers.

Using Do/While Statement:


Q5: What are the output of the following segment of C++ code:
int i;
i = 12;
do
{
cout << i << end I;
i --;
}
while ( i> 0 );

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.

Using For Statement:


Q8: Write C++ program to read 7 marks, if pass in all marks (>=50) print
"pass" otherwise print "fail".
Ql 1: Write C++ program to add the numbers between 1 and 100 and find its
average.

Ql 2: Write C++ program to print the following figures:


1
3 3 3
5 5 5 5 5
7 7 7 7 7 7 7
9 9 9 9 9 9 9 9 9
7 7 7 7 7 7 7
5 5 5 5 5
3 3 3
1

+ + + + + + + + + +
+ + + + + + + + +
+ + + + + + + +
+ + + + + + +
+ + + + + +
+ + + + +
+ + + +
+ + +
+ +
+

Ql 3: Write C++ program to find e from the following series:


e = 1 + (1 /1 !) + (1 /2!) + (1 /3!) + ... + (1 /n!)

Ql 4: Write C++ program to find e from the following series:


e = 1 + x + (x2 / 2!) + (x3 / 3!) + ... (x3 / a!)

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".

Ql 6: What is the output of the following C++ segment of code:


for ( ; ; )
{
cout << "enter your number:";
cin >> x;
if ( x % 2 == 0 J continue;
if ( x % 3 == 0 J break;
cout << "Bottom of loop"<< end I;
}

Ql 7: What is the output of the following C++ segment of code:


=
for ( I O; I < 8; I ++ J
{
if ( I % 2 == 0 J cout << I + 1 << endl;
else if ( I% 3 == 0 J continue;
else if ( I% 5 == 0 J break;
cout << "end program \n";
}
cout << "end ... ";

Ql 8: Write C++ program to print the following figure:


1
2 1
3 2 1
4 3 2 1
5 4 3 2

Ql 9: Write C++ program to print the following searies:

1. Sum=1+22 +42 + ... +n 2


2. Sum=1-3x+sx-... +nx
3. Sum=1 + 1/1! +2/2!+3/3! + ... +n/n! where n!=1 *2*3* ... *n

You might also like