Computer Programming 2024-2025
Computer Programming 2024-2025
Monitor
(Output Device)
RAM
(Main Memory)
Hard Disk
(Secondary Storage)
Keybord W P
(Input Device) /" (Processor) _g
Flash Disk
/% ;Z {Secondary Storage)
hardware componentis
human beings.
computer programs.
computer.
The following is a short history, just for given a general view of how languages
are arrived:
1954: Fortran.
e 1957: Cobol.
e 19588: Algol (Base for Simula).
e 1958: Lisp.
e 1961:B1000.
e 1962: Sketchpad.
e 1964:Basic.
e 1967:Simulaé7.
e 1968: FLEX.
e 1970: Pascal [From Algol).
o 1971: C (From alanguage called 8).
e 1972:Smalltalk72 (Based on Simulad? and Lisp).
e 1976: Smalltalk7é.
e 1979: ADA [From Pascal).
e 1980: C with classes (experimental version).
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).
types.
Object File
file-name.obj
Format: Binary
\4
Loader
LECTURE 2
L. Algortthm
As stated earlier an algorithm can be defined as a finite sequence of
be executed.
Algorithm properties:
e Finiteness: I1he ’clgorifhm must terminate a finite number of steps.
e Non-ambiguity: each step must be precisely defined. At the
completion of each step, the nest step should be uniquely determined.
e "Read a number".
e "Add a numberto anther number".
e "Output a number".
begin
Add the number to the accumulated sum.
increment the count of numbers entered.
7. Read next number.
8. End
9. Evaluate the average.
Example 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:
o |Initialize.
e Get count of numbers.
e Enter numbers and find maximum and minimum .
e 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:
Output result.
N
End.
©
2. Floweharts
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
Connector symbols
Example 1:
Draw a flowchart to read 3 numbers: x , y and z and print the largest
number of them.
Example 2:
Draw the flowchart required to find the sum of negative numbers
among 50 numbers entered by the user.
counter
End
AN INTRODUCTION
Q1: What do you means by program?
1 Character set:
C++ has the letters and digits, as show below:
Digits: 0,1,2,...9
( [ { } ]
) < = > , (Comma)
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 tdentifiers:
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
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.)
i (1 char.)
B (1 char.)
Examples of invalid identifiers are:
3ab af)test ros sal
3 Kegwoms:
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:
4Cownstawnts:
There are three types of constants: string constants, numeric constants,
(a)Integer constants: Do not contain decimal points: int x,y; shortint x,y;
longint x.y;
» Integer data: size (16 or 32) fill in -215 to 2'%-1 for 16 bit and -2°1 to
231-1 for 32 bit.
> Short integer: fill in -215 to 215-1.
» Long integer:fillin -231 to 231-1.
» Unsigned: fill in {0 to 65635) for 16 bit and (0 to 4,294, 967, 295) for
32 bit.
» Double 8 bytes.
» Long double 12 or 16.
(c)Hexadecimal constants: Hexadecimal numbers are integer numbers of
\n New line. Position the screen cursor to the beginning of the next
line.
\t Horizontal TAB (six spaces). Move the screen cursor to the next tab
stop.
\ Caniage 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 system bell.
\b Back space
\v Vertical tab
\? question mark
metic operators
Assignment operators
evaluated:
+ addition - subtraction * multiplication
/ division % modula {remainder of an integer division)
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 fo 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
assign 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.
C=3*(d=12.0/x);
Rewrite the equivalent statements for the following examples, and find it
results. Assume: X=2,Y=3,1=4,V=12,C=8.
1 1
m[=|n|—=
m|n|n|—=
1 0
(=]
|10
0 0
o=
0 0
OR(| |) Table: OR(| |) Table:
T T T [ [ [
T F T 1 0 1
F T T 0 1 1
F F F 0 0 0
NOT (1) Table: NOT (1) Table:
T F I 0
F T 0 1
Examples:
Example 1:
a=4, b=5, c=6
Example2:
Assume: X=0, Y=1, I=1. Find the following expression:
M= +4X | | ++Y &8& ++1
M= ++X || ++Y
&& ++Z
=il @y
=TI (T &&T)
TINT
T
1
>> 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
1 00001000 the resultant bit pattern willbe (0000 1000)
X=5,y=2 — x&y (0000) , x|y (0111) , xAy (0111)
(e)special operators:
1. Unary operator:
- Decrement.
Type | Forced type of conversion
Size of | Size of the subsequent data type or type in byte.
e=false
Comma operator: (,)
Int ab,c; or it is used in control statements
Scope operator: (i) It is used in a class member function definition.
5. New and delete operators: it is a method for camying out memory
allocations and deallocations.
6. Other operators: parentheses for grouping expressions, membership
operators.
&.Type Conversiow:
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; float y; x=y; Result =(int) (19.2/4); or
1 Statements:
A statement in a computer carries out some action. There are three
Begin
Type or variable declaration
Statements of operation
Results
end
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;
& #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 cinand cout mustinclude the header file lostream.
& 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 caling function.
Some programmers use int as a retum type for the main function, in this case a
return(0) staterment must be written as a last statement of the main function-body.
& [/, 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
Insertion
or Send
Operator
ex: cout<<“C++ Language”
& cin, the input stream object. It reads the input values from the keyboard.
Extraction
or Get from
Operator
keyboard
ex: cin>>x;
& >>, the stream exiraction operator (or get from operator].
The endl is used in ct++ to represent a new line, as shown in the following
example:
#Include<iostream.h> Output:
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:
#include<iostream.h> Quiput:
void main() hallow
{ students
cout << “hallow \n™;
cout << “students”;
3 variables declaration:
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.
variahle
haine Content | Address
x 70
Qoo 03F
The variable must be declared by specifying the datatype and the identifier.
datatype id.1, id2, ...,idn;
Example §
B the following program reads three different inputs and outputs it.
#include<iostream.h>
void main() OQutput:
4 Constants:
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.14;
const float salary=20.5;
Example é
,Q\ Write a program that reads the radius of a circle, then computes and
outputs its area.
#includec<iostream.h> 0
! I utput: ;
void main()
enter the radius of circle: 5
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:
Lecture 5
Example 1:
Write the following equation as a C++ expression:
f= a+h+c+d+e
10
Solution:
f=(@+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-VY;
Solution:
L+ Z=P*RO0Q
25 +W/X-Y;
Vi
w
~ .0
>
M)
wN
“L
Example 1
Write C++ program to perform the above equation:
#include<iostream.h>
void main( )
{
intZ, PR Q W X Y;
cout << " " cin >> P;
cout << ™ cin>> R;
cout << " cin>> Q;
cout << " cin >> W;
cout << " cin>> X;
cout << "enter Y:"; cin>>Y;
I=P*R%LQ+W/X-Y;
cout << "the result="<< Z;
2 The “math.h” L’vaavg:
The "math.h” library contains the common mathematical function used in the
scientific equations.
eh Exp(x)
Log(x) Log10(x)
Ln(x) Log(x)
Sin(x) Sin(x)
xn Pow(x,n)
VX Sqrt(x)
Example:
Write the following equation as a C++ expression and state the order of
evaluation of the binary operators:
sin(x) - x°
In(x) + 5
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) + xM))
| S—
3 4
I—I
IT‘
Exercise:
Write the following equation as a C++ expression and state the order of
evaluation of the binary operators:
x2 ¥y -3sin(x)
tanx3 +x31y
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
2 Ma wi_puLath Functions:
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” << endl;
(b)Setbase: It is used to convert the base of one numeric value into a
nother base
Dec(base 10), hex(base 14), oct{base 8)
Example 2
Write C++ program to convert a base of a number:
#include<iostream.h> Enter number
void main( ) 10
{ Decimal base=10
int value; Hexadecimal base=a
cout << "enter number:"; cin >> value; Octal base=12
cout << "Decimal base="<<dec<<valve<<endl;
cout << "Hexadecimal base="<<hex<<valve<<endl;
cout << "Octa base="<<ocic<valve<<end!
Example 4
B write c++ program to use setw:
#include<iostream.h>
#include<iomanip.h> 200 300
void main( void) 200 300
{
inta,b;
a=200;
b=300;
coute<setw(5)<<a<<setw(5)<<b<<endl;
cout<<setw(é)<<a<<setw(4)<<b<<endl;
Q8: What are the main types of variables, its sizes, and its range of
values?
Q12 What are the main keywords are includes in iostream.h and
math.h?
Q13: What are the main difference between prefix and posifix notation?
Q17: Given that A and B are real variables with values 1.5, and 2.5
Q19: Write a program to read a set of (§) real no.s and find out the
sum and average of them.
LECTURE 6
1. Selection Statemwents:
Conditional expressions are mainly used for decision making. C++ provides
multiple selection structures: if, if/else, else if, nested if and switch.
@ statementl
Example 1: if (awrg>=3.5)
cout << “good”;
Example 2: if (x>0.0)
sum += x;
fue alse
Statement 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
Example 4
B write a c++ program to read a number, and check if it’s even or
odd:
#include<iostream.h>
void main()
{
int num;
cin>> num;
if(num%2 ==0)
cout << "even™;
else
cout << “odd™;
5. Else if Statements:
Example 1:
if (value ==0) cout << “gradeis A”;
elseif (value==1) cout << “gradeisB”;
elseif (value ==2) cout << “grade isC";
else cout << “grade is X";
B write a c++ program to read a number, and print the day of the
week:
#include<iostream.h>
void main( )
{
int day;
cin >> day;
if(day==1) cout<< “Sunday”;
cout << “Monday”;
cout << “Tuesday”;
cout << “Wednesday”;
cout << “Thursday™;
cout << “Friday™;
cout << “Saturday™;
else cout << “Invalid day nhumber™;
}
,Q\ Write C++ program to compute the value of Z according to the
following equations:
x+5 tx<0
Z={cos(x)+4 x=0
Vx x>0
#include<iostream.h>
void main( )
{
intZ, x;
cout << "Enter X value \n";
cin>>x;
if(x<0) I=x+5;
elseif (x==0) I= cos(x) + 4;
else Z= sqri(x);
cout << "Zis" << I;
}
#include<iostream.h>
void main()
{
#include<iostream.h>
void main( )
{
Float x,y,z
Cout<<”Enter any two numbers\n";
Cin>>x>>y,z;
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
switch ( sefector)
{
case /abell : statementl; break;
case /abel2 . statement?; break;
case /abel3 : statement3; break;
Example 2
Write C++ program to read two integer numbers, and read the
operation to perform on these numbers:
#include<iostream.h>
void main()
{
inta, b;
char 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;
}
case /abel-n . statement-n; break;
default : statement-e; break;
)
Example 3
B write c++ program to read integer number, and print the name of
the computerized department:
#include<iostream.h>
void main( )
{
intij;
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)
3. conditional Statewent:
Example 2: cin>>x>>vy;
cout<< (x<y?-1:(x==y?0:1));
Example 4
B write c++ program to read integer number, and print if its even or
odd:
#include<iostream.h>
void main()
{
int valve;
cout << “Enter the number \n";
Cl in >> value;
cout<<(valve%%2==0?"even":"odd");
}
WORK SHEET (3)
Selection Statements
Q1: 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.q:
0 »Zero
10ne
2 FTwo
Q3: Write C++ program to read a score of student and print the estimation
to refer it.
eq:
100 - 90 = Exulfant
89-80 3 Very good
79-70 # Good
49 - 60 = Middle
59-50 3 Accept
49- 0 Fail
Q& Write C++ program to compute the area of circle if the radius r=2.5.
Note: area of circle isr *r * pi,
piis 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 (AB, ... .Z), small letter (a, b, ... ,z), special character [+, |,
@ #{>..)
Q10: Write C++ program to read x and compute the following:
2
Xx<+5x- 20 B
- ifx>0
¥ 2x
Y= 0 ifx=0
x2 +(5x)2-10 ifx<0
Qlz: Write C++ program to read two integer numbers, and read the
operation to perform on these numbers.
Q13: Write a program to read X and print Sin X if X>0, square root X f X<0
and absolute X if X/2is integer.
LECTURE 8
1. Loop Statewents:
The loop statements are essential to construct systematic block styled
programming. C++ provides three iteration structures: while, do/while, and for.
while (condition )
statementd ;
while (condition )
{
statementd ;
statement2 ;
statement-n ;
¥
T
@ Statement 5
Example i=0;
1: while (i< 10)
{ Qutput:
. 01234567829
cout << i; =10
i++; =
Example i=0;
2: while (i< 10)
{ Output: even numbers only
cout << j; 02468
i+=2 =10
}
Example i=1;
3: while (i< 10)
{ Output: odd numbers only
cout<<i; 1357¢9
i+=2; =11
}
#include<iostream.h>
void main( )
{
int count=1;
intsum=0;
while ( count<=19% )
{
sum = sum + count;
count = count + 2;
}
cout << “sum is: “ << sum << endl;
}
cout << “sumiis: “ << sum << endl;
}
,Q\ Write C++ program to find the summation of student’s marks, and
it's average, assume the student have 8 marks:
#include<iostream.h>
void main()
{
int mark, i, sum=0;
floatav=0;
i=1;
while (i<=8)
{
cout << “enter mark: “;
cin >> mark;
sum = sum + mark;
i+
}
cout << “sumiis: “ << sum << endl;
av=sum/8;
cout << “average is: “ << av;
Example 5
B write c++ program that display the following board pattern:
T R
®
B
®
B
%
%
%
%
T
%
%
¥
%
*
o#
o®
®o#
#o®
LR
%
#
®
L
#include<iostream.h>
void main( )
{
introw = 8, column;
while (row-->0)
{
column=8;
if(row%2==0)
cout <<
while ( column-->0)
cout << “¥.
cout << ‘\n’;
}
Example é
B wiite c++ program to check for a line feed and tab of a given
character:
#include<iostream.h>
void main()
{
Char ch;
Cout<<”enter a line \n";
Ch=cin.geX);
While (chl="\n’ && chl="\t")
{ cout.put(ch);
Ch=cin.gef); }
2. Do / wWhile Statewent:
General Form of Do / While statement:
do
statement! ;
while (condition );
do
{
statement! ;
statement2 ;
statement-n ;
while (condition );
Statement s
Example 1:
Quiput:
0128345678¢9
cout << j;
=10
i++;
}
while (i< 10)
Example 2:
}
while (i<=8)
cout << “sum is: “ << sum<< endl;
av=sum/8;
cout << “average is: “ << av;
Example ¢
,Q\ Write C++ program to find the factorial of n:
nl=n*n1*n2*n3*...%2*%1
#include<iostream.h>
void main( )
{
intn f=1;
cout << “enter positive number: “;
cin>> n;
do
{
while (n>1);
cout << “factorial is: “ << f;
}
Example 10
B write c++ program to find the summation of even numbers
#include<iostream.h>
void main()
{
int max,sum,digit;
digit=2;
cout << “enter a number: “;
cin >> max;
sum=0;
do
{
Sum=sum+digit;
Digit+=2;
while ( digit<=max );
cout << “2+4+...="<<max<<"sum="<<sum<<endl; }
LECTURE 9
1. For Statement:
General Form of For statement:
Example 1
B write c++ program to add the numbers between 1 and 100:
#include<iostream.h>
void main( )
{
intsum=0;
for(inti=1;i<=100;i++)
sum=sum +i;
cout << “sum is: “ << sum;
Example 2
,Q\ Write C++ program to find the factorial of n {using for statement):
nl=n*n-1*n2*n3*...%2*%1
#include<iostream.h>
void main()
{
intn, f=1;
cout << “enter positive number: “;
cin>> n;
for(inti=2;i<=ni++) ¥ for(inti=n;i>2;i--)
F=f*i
cout << “factorial is; “ << f;
}
Example 3
B write c++ program to the result of the following:
20
#include<iostream.h>
void main()
{
intsum=0;
for(inti=1;i<=20;i++)
sum=sum+(i*i);
cout << “The sumis: “ << sum;
}
Example 4
B write c++ program to read 10 integer numbers, and find the sum
of positive number only:
#include<iostream.h>
void main()
{
intnum, sum=0;
for(inti=1;i<=10;i++)
{
cout << “enfer your number: “;
cin >> num;
f(num>0) sum=sum+num;
}
cout << “The sumis: “ << sum;
Example §
B write c++ program to print the following series: 1, 2, 4, 8, 16, 32, 64
#include<iostream.h>
void main( )
{
intx;
for(x=1;x<é5x*=2)
cout &< x <<
}
#include<iostream.h>
void main( )
=
=RV
{
intx;
R
for(x=1;x<7;++x)
cout &< x <<"\1* << 11 - x << endl;
[
}
Example 7
,Q\ Write C++ program to read a line using for loop
#include<iostream.h>
void main( )
{
Char ch;
cout << “Enter a line\ n“;
for (;(ch=cin.get())!="\n";) {
cout<<"Y
our character is:"<<endl;
cout.put(ch);
}
}
loopa
=1
#include<iostream.h>
void main( )
{
inti, j, sum=0;
for(i=1;i 5 i++)
for(j=1;j<=10;j++)
sum=sum+(i+2*j)
cout << “sumiis:” << sum;
}
Example ¢
B write c++ program to print the following figure:
L G
PEr s
EEFHEE
R
YW
st
+
#include<iostream.h>
void main( )
{
inti, j;
for(i=1;i<=10;i++)
{
for(j=Lj<=ij++)
cout k< “+
cout << “\n*;
}
}
Example 10
B write c++ program to read a line using for loop
#include<iostream.h>
void main( )
{
cout << “Explaining the nested for loop\n*;
for (int i=0;i<=2;i++) {
cout<xi;
for (int k=0;k<=2;k++) {
coute<”computer sciences department \n”;
Pl
Exercise:
What is the oulput of the following C++ program ?
#include<iostream.h>
void main( )
{
inti, 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
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
#include<iostream.h>
void main( )
{
int valve,i;
i=0;
while (i<=10) {
cout<<"enter a number \n";
cin>>value;
if (value<=0) {
cout<<"Zero or negative value found \n";
brek;
}
j++
}
}
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 emor and it continues the same loop as long
2. Conditional Goftoe: Itis 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:
#include<iostream.h>
void main( )
{
Int value,i=0;
While i<=10) {
Cout<<”enter a number \n";
Cin>>value;
Cout<<"zero or negative value found \n";
Goto error;
Error:
Cout<<"input data error \n"”;
}
s=s+i;
i
f=f*i
i++;
Q4: Read 10 numbers, and find the sum of the positive numbers only.
for(i=1;i<=10;
i++) i=1; =13
£ while (i <= 10) do
cin >> x;
{ 3
if(x>0) s=s+x; g, cin >> x;
} if(x>0) s=s+x; if(x>0) s=s+x ,
e i++;
¥ }
while (i <= 10);
Q5: Represent the following series: 1, 2, 4, 8, 16, 32, 64.
Q7: Find the sum and averag; e of the 8 degrees of the student.
for(i=1;i<=8; i++) i=1;
L while (i<=8)
cin >> d;
s=s+d; cin >> d;
3 s=s+d;
av=5/8; i++;
av=s5/8;
av=s/8;
Q8: Find the cub of n numbers, while the entered number is a positive.
cin >> x; do
while (x> 0) {
Cant be solve this problem 1 cin >> x;
using For statement C= X FNTx: e=x%n¥y
cin >> X; }
¥ while (x> 0);
WORK SHEET (4)
Iteration Statements
Q4: Write C++ program to display the first 100 odd numbers.
}
while (i>0);
Qé6: What are the output of the following segment of C++ code:
intcount=1;
do
{
cout << {count % 27 "+ “+++++") << 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 s 10 100 1000
2 20 200 2000
3 30 300 3000
4 40 400 4000
Hint\t fo print six spaces.
WONONO W =T
woNvNG W
waNe W
nNe NG,
NG,
N
~Ne~
~e~
-
-
BN
BB EEE RN
e
(RN
FEE
PR R
BEE
W
Ql1s: 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”.
1. Sum=142°+4%+..+n?
2. Sum=1-3+5-..+n*
3. Sum=1+1/11+2/21+3/3!+..
+n/n! where nl=1¥2%3*_*n
LECTURE 11
1. Functions:
A function is a set of statements desighed to accomplish a particular
task. Experience has shown that the best way to develop and maintain a
large program is to construct it from smaller pieces or [modules). Modules in
C++ are called functions.
Functions are very useful to read, write, debug and modify complex
programs. They can also be easily incorporated in the main program. In C++,
the main{() itself is a function that means the main function is invoking the
2. Defining a Function
A function definition has a name, parentheses pair containing zero or
more parameters and a body. For each parameter, there should be a
comesponding declaration that occurs before the body. Any parameter not
declared is taken to be an integer by default. The general format of the
function definition is :
General Form of Function:
return-type function-name ( parameters-list )
{
(body of function)
statementl ;
statement2 ;
statement-n ;
(retumn something)
The type of the function may be int, float, char, etc. It may be declared
as type (void), which informs the compiler not to the calling program. For
example:
Void function_name (---)
Int function_name (---)
Any variable declared in the body of a function is said to be local to that
function. Other variables which are not declared either as arguments or in the
function body are considered “global”’ to the function and must be defined
externally. For example
Void square (int q, int b) — a,b are the formal arguments.
Float output (void) — function without formal arguments
Example 1: Example 2:
Example 1
Write C++ program to calculate the squared value of a number
passed from main function. Use this function in a program to calculate
the squares of numbers from 1 to 10:
#include<iostream.h>
int square (inty )
{
intz;
z=y*'y;
return(z);
}
void main( )
{
intx;
for(x=1; x <= 10; x++)
cout << square ( x ) << endl;
Example 2
B write c++ program using function to calculate the average of two
numbers entered by the userin the main program:
#include<iostream.h>
float aver (int x1, int x2)
float z;
z=(x1+x2)/2.0;
return ( z);
}
void main()
{
float x;
int numl,num2;
cout << "Enter 2 positive number \n";
cin >> num1 >> num2;
x = aver (numl, num2};
cout << x;
Example 3
B write c++ program, using function, to find the summation of the
following series: D
L 221242432
a2
i=1
#include<iostream.h>
int summation (int x)
{
inti=1,sum=0;
while (i<=x)
{
sum+= i*i;
i++;
}
return (sum);
}
void main ( )
intns;
cout << "enter positive number”;
cin>>n;
s =summation(n};
cout << "sumis: " << s << endl;
Example 4
#include <iostream.h>
int max(inty1, int y2, int y3)
{
int big;
big=y1;
if (y2>big) big=y2;
if (y3>big) big=y3;
return (big);
}
void main()
{
int largest x1,x2,x3;
cout<<"Enter 3 integer numbers:";
cin>>x1>>x2>>x3;
largest=max({x1,x2,x3);
cout<<largest;
}
#include<iostream.h>
void ANDF(int,int);
void ORF(int,int);
void XORF(int,int);
void NOTF(int);
void main()
{ char s;int q,b;
cout<<"Enter the value A,B:";
cin>>a>>b;
cout<<"Enter the select valve \n™;
cout<<"\ta--(AND gate)\ n\to--(OR gate)\n\tx--(X-OR)\ n\tn--(NOT
gate)\n\te--(<<EXIT>> :";
cin>>s;
switch(s)
{
case 'aANDF(a,b);break;
case '0":ORF(a,b);break;
case 'x:XORF(a,b);break;
case 'n":NOTF(a);cout<<" ";NOTF(b);break;
case 'e:break;
deafult:cout<<":bad choose™
}
}
void ANDF(int a,int b)
cout<<(a&&b);
cout<<(a| | b);
cout<<(aAb);
}
void NOTF(int a)
{
cout<<(la);
}
4. Passing Paraweters:
There are two main methods for passing parameters to a program:
1) passing by value, and 2) passing by reference.
B- Passing by Reference:
When parameters are passed by reference their addresses are copied
to the corresponding arguments in the called function, instead of copying
their values. Thus pointers are usually used in function arguments list to receive
passed references.
This method is more efficient and provides higher execution speed than the
call by value method, but call by value is more direct and easy to use.
Example é:
The following program illustrates passing parameter by reference.
#include <iostream.h>
void swap(int *a,int *b)
{
intt;
t=*a;
*a=*b;
*b=t,
}
void main( )
{
int x=10;
inty=15;
cout<<"x before swapping is:"<<x<<"\n";
cout<<"y before swapping is:"<<y<<"\n";
swap(&x,&y);
cout<<"x after swapping is:"<<x<<"\n";
cout<<"y after swapping is:"<<y<<"\n"; }
LECTURE 12
1. T s of Functions:
The user defined functions may be classified in the following three ways
based on the formal arguments passed and the usage of the return
statement, and based on that, there are three of user defined functions:
calling portion of a program and also the function does not return back
any valve to the called function.
2. A function is invoked with formal arguments from the calling portion of
a program but the function does not return back any value to the
calling portion.
3. A function is invoked with formal arguments from the calling portion of
Example 1:
# include <iostream.h> # include <iostream.h>
Void main() Void main()
{ {
Void square (int); float square (float);
Int max; float I, max,value;
Cout<<”Enter a value for n 2\n";
Cin>>max;
For (int i=0;i<=max-1;++i) while (i<=max) {
Square (i) value=square(i);
} Coutec”i="ecjc<"square="<<value<<endl;
Void square(int n) I=i+0.5;
{ }
Float valve; }
Value=n*n; Float square(float n)
Couteg”j="<<n<<"square="<<value<<endl; {
} Float value;
Value=n*n;
Return (value);
}
Example 2:
,Q\ write C++ program, using function to find the sumation of the given
series: Sum=x-[x3)/3l+ (x5)/5!- ... (x)/n!
#include <iostream.h>
Void main(void)
{
Long int fact (int);
Float power(float,int);
Float sum,temp,x,pow;
Int sign,l,n;
Longint factorial;
arguments:
(a)Actuadl arguments: An actual argument is a variable or an expression
contained in a function call that replaces the formal parameter which
Local variables are referred only the particular part of a block or a function.
Same variable name may be given to different parts of a function or a block
same name through out the program in both the calling portion of the
program and in the function block.
,Q\ A program to find the sum of the given two numbers using the global
variables.
#include <iostream.h>
Int x;
Int y=5;
void main( )
{
X=10;
Void sum(void);
Sum();
}
Void sum(void)
{
Int sum;
Sum=x+y;
Coutc<”x="<<x<<endl;
Coutc<"y="<<y<<endl;
Coute<”sum="<<sum<<endl;
4. Recurstve Functions:
A function which calls itself directly or indirectly again and again is
known as the recursive function. Recursive functions are very useful while
constructing the data structures like linked lists, double linked lists, and trees.
normal function will be invoked by the main function whenever the function
name is used, where as the recursive function will be invoked by itself directly
or indirectly as long as the given condition is satisfied. Forexample,
# include <iostrem.h>
Void main(void)
Example 4:
jmu
= A program to find the sum of the given non negative integer numbers
using d recursive function sum=1+2+3+4+...+n
#include <iostream.h>
Void main(void)
{
Int sum(int);
Int ntemp;
Coute<”Enter any integer number’<<endl;
Cin>>n;
Temp=sum(n);
Cout<<"value="<<n<<"and its sum="<<temp;
,Q\ A program to find the factorial (n!) of the given number using the
recursive function.lts the product of all integers from 1 to n {n is non negative)
(so n!=1if n=0 and n!=n(n-1] if n>0)
#include <iostream.h>
Void main(void)
{
Long intfact (long int);
Int x,n;
Cout<<"Enter any integer number’<<endl;
Cin>>n;
X=fact(n);
Coutc<"value="<<n<<"and its fa ctorial=";
Coute<x<<endl;
Q2 Write a C++ program, using function, that reads two integers (feet and
inches) representing distance, then converts this distance to meter.
Note: 1foot =12 inch
linch=2.54Cm
iLe.:
Input: feet: 8 orinches: 9
Q3: Write a C++ program, using function, which reads an integer value (T)
representing time in seconds, and converts it to equivalent hours (hr),
minutes ([mn), and seconds (sec), in the following form:
hr: mn:sec
e
Input: 4000
Output: 1:6:40
Q4: Write a C++ program, using function, to see if a number is an integer
(odd or even) or not an integer.
QS Write a C++ program, using function, to represent the permutation of n.
Qé: Write a C++ program, using function, to inputs a student’s average and
returns 4 if student’s average is 90-100, 3 if the average is 80-89, 2 if the
average is 70-79, 1 if the average is 60-69, and 0 if the average is lower
than 60.
Q7: The Fibonacci Series is: 0, 1, 1, 2, 3, 5, 8, 13, 21, ... It begins with the
terms 0 and 1and has the property that each succeeding term is the
sum of the two preceding terms. Write a C++ program, using function,
to calculate the nth Fibonaccinumber.
Write C++ program, using function, to convert any char. from capital
Ql4:
to small or from small to capital.
Q18:
Write C++ program using recursive function to find the power of n
numbers.
LECTURE 13
1. Armgs:
An array is a consecutive group of homogeneous memory locations.
Each element (location) can be referred to using the aray name along with
an integer that denotes the relative position of that element within the amray.
The data items grouped in an amray can be simple types like int or float, or
array-name content
The item in an amray are called elements (in contrast to the items in a
structure which are called members). The elements in an array are of the
-intx[1={128,50,11,7,30,100,22};
Example 2
Write C++ program to read 5 numbers and print it in reverse order:
#include<iostream.h>
void main( )
int a [5];
cout << "Enter § numbers \n";
for (inti=0;i<5;i++)
{
cout << << ¢
cin>>alil;
cout << “\n";
Example 4
B write c++ program, to find the minimum value in array of 8
numbers:
#include<iostream.h>
void main ()
{ intn=8; inta[ ]={18,25,36,44,12,60,75,89});
itmn=a[0];
for (inti =0;i <n;i++)
if(a[i]<min) min=alil;
cout << "The minimum number in array is: " << min;
#include<iostream.h>
void main ( )
{
Int month, day, total_days;
Int days_per_month[12]={31,28,31,30,31,30,31,31,30,31,30,31}
Cout<<"\ n Enter month(1 to 12):";
Cin>>month;
Cout<<"enter day(1 to 31):";
Cin>>day;
Total_days=day;
For (int j=0;j<month-1;j++)
Total_day+=day_per_month[j];
Cout<<"Total days from start of year is:"<<total_days;
}
#include<iostream.h>
#include<iostream.h>
void main ( )
{
ita[20]={1,2,3,4,5,6,7.8,9,10,11,12,13,14,15,16,17,18,19,20};
int aodd[20], aeven [20];
inti,0=0, e=0;
for (i=0; i<20; i++ )
if (a[i] %2 !=0)
{
aodd[o]=ali];
o=o+1;
}
else
{
aevenle]=ali];
e=etl;
}
for (i=0;i<o; i++)
cout<<aodd[i]<<" ";
cout<<end!;
for (i=0;i<e; i++)
cout<<aeven[i<<"
LECTURE 14
1. Avray of Two Dimension:
Arrays can have higher dimension. There can be arays of two
dimension which is aray of arrays. It is accessed with two index. Also there
can be arays of dimension higher than two.
£4
~
W
o
a
row | 110Ny
for(i=0;i<3;i++)
{
for(j=0;j<5;j++)
cout<<alilljl;
cout
<< endl;
}
}
= Write C++ program, to read 4*4 2D-armay, then find the summation
of the aray elements, finally print these elements:
#include<iostream.h>
void main ( )
{
inta[4][4]
inti,j, sum=0;
for(i=0;i<4;i++)
for (j=0;j<4;j++)
cin>>alillil;
for(i=0;i<4;i++)
for (j=0;j<4;j++)
sum+=ali][jl:
cout << “summation is: “ << sum << end|;
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
cout<<alilljl;
cout
<< endl;
}
Example 3
B write c++ program, to read 3*4 2D-amay, then find the summation
of each row:
#include<iostream.h>
void main ()
inta[3][4]
inti,j, sum=0;
for(i=0;i<3;i++)
for(j=0;j<4;j++)
cin>>alillijl;
for(i=0;i<3;i++)
{
sum=0;
for(j=0;j<4;j++)
sum+=ali]l[jl;
cout << “summation
of row “ << i << “is: “ << sum << endl;
Write C++ program, to read 3*4 2D-amray, then replace each value
equal § with 0:
#include<iostream.h>
void main ( )
{
inta[3][4];
inti,j;
for(i=0;i<3;i++)
for(j=0;j<4;j++)
cin>>alilljl;
for(i=0;i<3;i++)
for(j=0;j<4;j++)
if (a[i]l[jl==5) alillil=0;
for(i=0;i<3;i++)
for(j=0;j<4;j++)
cout<<alilljl;
cout
<< endl;
}
Example 5§
B write c++ program, to addition two 3*4 arrays:
#include<iostream.h>
void main ()
{
ita[3][4].b[3][4].c[3]1[4]
inti,
cout << "enter element of array A: \n";
for(i=0;i<3;i++)
for(j=0;j<4:j++)
cin>>alilljl;
cout << "enter element of array B: \n";
for(i=0;i<3;i++)
for(j=0;j<4;j++)
cin>>bl[illjl;
for(i=0;i<3;i++)
for(j=0;j<4:j++)
clillil=alillil*b[il[il;
for(i=0;i<3;i++)
for(j=0;j<4;j++)
cout<< c[ill[il;
cout
<< endl;
Example é
B write c++ program, to convert 2D-array into 1D-amray:
#include<iostream.h>
void main ( )
{
ita[3][4]
intb[12];
inti,j, k=0;
for(i=0;i<3;i++)
for(j=0;j<4;j++)
cin>>alilljl;
for(i=0;i<3;i++)
for(j=0;j<4;j++)
b[kl= alillil
k++;
}
for(i=0;i<k;i++)
cout<<
b [il;
}
B write c++ program, to replace each element in the main
diameter (diagonal) with zero:
#include<iostream.h>
0,0
void main ()
11
inta[3][3];
inti,j; 2,2
for(i=0;i<3;i++) - "
for (j=0:j<3;j++) =1
cin>>alillil;
for(i=0;i<3;i++)
for (j=0;j<3;j++)
if(i==j) ali]llil=0;
for(i=0;i<3;i++)
for(j=0;j<3;j++)
cout<<alilljl;
cout
<< endl;
}
T1 (12 | [0 |11
22 | (20 21 (2,2
i>j i<j
Example 8
B write c++ program, print the square root of an array:
#include<iostream.h>
void main ( )
ita[3][3],b[3][3]
inti,
for(i=0;i<3;i++) {
for(j=0;j<3;j++) {
blillil= sar(alil[il):
cout<<b[i][jl;
4 Sl
Example ¢
Write C++ program, to read 3*3 2D-array, then find the summation
of the main diagonal and its secondary diagonal of the amray
elements, finally print these elements:
#include<iostream.h>
void main ( )
{
inta[3][3];
inti,j.x,y
for(i=0;i<3;i++) {
for(j=0;j<3;j++) {
cin>>alillil;
it{i==]}
x=x+a[i][jl;
if (i+j=4)
y=y+alillil:
} o}
cout << “summation of diagonal is: “ << x << endl;
cout << “summation of inverse diagonal is: “ << y << endl;
WORK SHEET (6)
Arrays
Ql: Write a C++ program, using function, to find if the amray’s elements are
in order or not.
Q3 Write a C++ program, using function, to find the value of aray C from
add aray Aand amray B. Cli]=A[i]+BI[il;
Q4: Write a C++ program, using function, to multiply the aray elements by
2. Alil=ALI]1*2
Qé: Write a C++ program, using function, to merge two arrays in one array.
Q7: Write C++ program, to read 3*4 2D-array, then find the summation of
each col.
Q8: Write C++ program, to replace each element in the second diameter
(diagonal) with zero.
Q9: Write C++ program, to replace the elements of the main diameter with
the elements of the second diameter.
Q10 Write C++ program, to find the summation of odd numbers in 2D-array.
Qll: Write C++ program, to find (search) X value in 2D-array, and return the
index of it’s location.
Q12 Write C++ program, to convert 1D-array that size [16] to 2D-array that
size of [4] [4].
Q17: Write C++ program, to exchange row1 and row3 in 4*3 array.
Ql18: Write C++ program, to exchange row0 with col3 in 4*4 array.
Q19: Write C++ program, to find the greatest number in the second
diagonal, in 3*3 amray.
Q20: Write C++ program, to read X[ n ], and rotate the elements to the left
by one position.
Q21: Write C++ program, to read A[ n ] and a location I then delete the
number at location Z from the array, and print the new array after
deletion.
Q22: Write C++ program to order the amray in ascending and descending
order.
Q23: Write C++ program to read (n) no.s and find the average of the even
no. on it.
Q24: Create the array (b) from (a).
123 6
4 5 6 10
7 829 10
1111 2111
2222 1211
3 333 11 21
4 444 1T 11 2