0% found this document useful (0 votes)
3 views98 pages

Computer Programming 2024-2025

The document provides an introduction to computer programming, focusing on the C++ programming language and its development process. It outlines the history of programming languages, the structure of algorithms, flowcharts, and key concepts such as identifiers, keywords, constants, and operators in C++. Additionally, it details the phases of C++ program development and includes examples of algorithms and flowcharts.

Uploaded by

Abdulla Basheer
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
3 views98 pages

Computer Programming 2024-2025

The document provides an introduction to computer programming, focusing on the C++ programming language and its development process. It outlines the history of programming languages, the structure of algorithms, flowcharts, and key concepts such as identifiers, keywords, constants, and operators in C++. Additionally, it details the phases of C++ program development and includes examples of algorithms and flowcharts.

Uploaded by

Abdulla Basheer
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 98

) sad) ad) 5 ol k) Aaasa

Subject: Computer Programming


First Stage

Lecturer: Asst. Huda Sabah Shuker


LECTURE 1
1. ntroduction:

Monitor
(Output Device)

RAM
(Main Memory)

Hard Disk
(Secondary Storage)
Keybord W P
(Input Device) /" (Processor) _g
Flash Disk
/% ;Z {Secondary Storage)

hardware componentis

Computer is a device capable of performing computations and making


logical decisions at speeds milions 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.

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

e 1983: C++ (by Bjarne Stroustrup).


e 1986: Objective-C (from C and Smaillalk).
e 1986: Eiffel {from Simuia).
e 1991:Sather (From Eiffel).
o 1991:Java.
Bjarne Stroustrup
e 2000: C#. at: AT&TLabs
3. C++ Prooramwming Language:
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++ Program Development 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. Lloading: The loader loads the program from the disk into memory.
6. CPU: Executes the program, residing in memory.
These steps are infroduced in the figure below:
Source File
file-name.cpp
Format: Text

Object File
file-name.obj
Format: Binary

Other Object Files


Format: Binary = e Executable File
Format: Binary
file-name.exe

\4
Loader
LECTURE 2
L. Algortthm
As stated earlier an algorithm can be defined as a finite sequence of

effect statemenis to solve a problem. An effective statement is a clear,

unambiguous instruction that can be camied out .Thus an algorithm should


special the action to be executed and the order in which these actions are to

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.

o Effectiveness: the algorithm should solve the problem in a reasonable


amount of time.

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


their average .
A computer algorithm can only carry out simple instruction like:

e "Read a number".
e "Add a numberto anther number".
e "Output a number".

Thus an algorithm is:


1. Carmy ovut initialization required.
Read first number.
While the number of numbers is not complete do
NG

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:

1. Initialize the require variables.


Get count of numbers.
oA~ N

If count is zero then exit.


Otherwise begin.
Enter numbers.
Find max and min.
o

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

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

Q2: Why C++ language becomes quite popular?

Q38: 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 0 to 10.

c. The multiplication of 10 numbers.


Lecture 3

1 Character set:
C++ has the letters and digits, as show below:

Uppercase: AB,C, ..., Z

Lowercase: a,b,c, ...z

Digits: 0,1,2,...9

Special Characters: All characters other than listed treated as special


characters for example:
+ - * / Pay

( [ { } ]
) < = > , (Comma)

™ (Doble Conations) . (Dot) * (Colon) 5 (Semicolon) L 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 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

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.)
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:

Some of C++ Language Reserved Words:


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

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

and character constants.

1. sting 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 constanis 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
Short integer (short)
Long integer {long)
Single precision (float)
Double precision (double)
Long double
Short hexadecimal
Long hexadecimal
Unsigned char
Unsigned integer
Unsigned short integer
Unsigned long integer
Short octal
Long octal

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

(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 numker (the mantissa) followed by the

letter E and e and an optionally signed integer (the exponent). Ex.


{9010e10, 77.11E-11).
» Float4 bytes.

» Double 8 bytes.
» Long double 12 or 16.
(c)Hexadecimal constants: Hexadecimal numbers are integer numbers of

base 16 and their digits are 0 to 9 and AtoF.


(d)Octal constants: Octal numbers are numbers of base 8 and their digits
areOto 7.
3. Character Constants: A character represented within single quotes

denotes a character constant, for example ‘A, ‘a’, *: , '8, et


Its maximum size is 8 bit long, signed, and unsigned char are three distinct
types.
Charx; charxy.z;
The backslash (\) is used to denote non graphic characters and other
special characters for a specific operations such as:

Special Escape Code:

\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

\\ Backslash. Prints a backslash character.


\f Form feed

\v Vertical tab

\7 Double quote. Prints a () character.


\o Null character

\? question mark

\ooo Octal value

\xhhh | Hexadecimal value


5. Ct++ operators:

metic operators

Assignment operators

Comparison and logical | Relational,equality,logical


operators

Bit wise logical operators

Special operators Unary, ternary, comma

Scope, new&delete, other

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

evaluated:
+ addition - subtraction * multiplication
/ division % modula {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.


* [/ multiplication & division.
+ - addition and subtraction.
Example: X+y*X-1, where X=5, Y=6, and 1=8.
5+ (6%5)-8 — (5+30)-8 — 358 27

2. Assignment Operators: The operatonal assignment operator has the


form:
Variable = variable operator expression;
Ex: x=x+5; y=y*10;

The operational assignment operator can be written in the following


form:
Variable operator = expression
Ex: x+=5; y*=10;

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

Left shift and assign fo the LHS.

Bitwise AND operation and assign fo LHS

Bitwise OR operation and assign o LHS

Bitwise complement operation and assign to LHS


This is a valid statements:
A=b=c+4;

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.

Example Equivalent Statement Result


X+=5 X=X+5 X€7
Y-=8 Y=Y-8 Y&-5
1*=5 1=1*5 I <
V/=4 V<&
C%=3 c <

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, I= not equal to
Ex: a=4, b=6, c=8. A==b—false, (a*b)!=c—true,'s’=="y’ —false.

(<) Llogical operators: The logical expression is constructed from relational


expressions by the use of the logical operators not(!), and(&&), or(]| | ).

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

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

(a<b)&&(b<c) | (a<b) | | (b>c) | fa<b)| [(c>b) | (a<b) | | (b>c)&&(a>b) | [ (a>c)


T T (T T moord T I F && F QL F
T T FogpT T Il F || F
T T || F
T

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

(d) Bitwise logical operator:


& bitwise AND, A bitwise exclusive OR(XOR), | 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
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:

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


& Address of a variable.
- Negative value (minus sign).

! Negative (0, if value # 0, 1 if value =0).


~ Bitwise complement.
++ Increment.

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

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
Else E=(v%2 ==0)¢ True : false

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

Result = int (19.2/4);


Lecture 4

1 Statements:
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=btc; a=l;
X=XFX; k=a+1;
y=atx; }
}

2 getting Stavted with ¢+ +:


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 |/O 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:


#include<iostream.h> Output:
void main()
Welcorne
{
// 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 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.

& { introducing the statements that define the function.

&} indicates the end of the statements in the function.

& [/, 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

¢—® routput list”


0}

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;

o <<, the streaminserfion operator {or send operator).

& >>, the stream exiraction operator (or get from operator].

& ;. semicolon, the terminator of every C++ statement.

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.

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.

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;

A variable defined by stating its type, folowed 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 q, c;

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


(C++ is case-sensitive).
Example 4
,Q\ 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";
char ch="a’; Character=a
cout << “character="<<ch<<”\n"; Real number=34.45
float fa=-34.45;
cout<<"real number="<<fa<<”\n";

Example §
B the following program reads three different inputs and outputs it.
#include<iostream.h>
void main() OQutput:

{ . input integer number &


intn; floatf, charc;
input decimal number: 4.2
cout << “inputinfeger number:"”;
input character: A
cin>>n;
cout<<endl;

cout << “input decimal number:”;


cin>>f;
cout<<endl;

cout << “input character:”;


cin>>c;

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

const float pi=3.14; the area of circle: 76.5


intr; float c;
cout << “enter the radius of circle:”;
cin>>r;
cout<<endl;
c=r*r*pi
cout << “the area of circle:” << ¢;

B 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
cin>> a>>b; A=10 b=20 sum=30
Sub=10
sum=a+b; Mul=200
sub=a-b; Div=0
mul=a*b;
div=a/b;
coutk<”g="<ka<<"b="<<b<<"sum="<<sum<<endl;
coutc<”sub="<<sub<<endl;
coute<"mul="<<mul<<endl;
coute<”div="<<div<<end|;
Example 8
B 1he following program computes different division operators.
#include<iostream.h> Output:
void main( )
{
intx, y,zr;
x=7/2;
cout << "x=" << x <<endl;
y=17/(-3);
cout << <<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:
Lecture 5

1 Exawples of order evaluation:

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.

Common function from math.h library:

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:

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 cumrent statement.

The difference between the Prefix and Postfix notations:


Prefix notation Postfix notation
inty; inty;
intx=7; intx=7;
cout<< ++x <<endl; cout<< x++ <<endl;
y=x; y=x;
cout<<y; cout<<y;

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!

When using setbase the statement will be:


Cout<<”Decimal base="<<setbase (10);
Cout<<value<<endl;

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

B write c++ program to use tab:


#include<iostream.h>
#lrfclude.<|omf:n|p.h> 200 300
void main( void)
{
inta,b;
a=200;
b=300;
coutegag<’\t'<<b<<endl;

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;

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


width of the value. Seffill(char f)
,Q\ Write C++ program to use seffill:
#include<iostream.h>
#include<iomanip.h> ##200%#300
void main( void) ##*200%*#300
{
inta,b;
a=200;
b=300;
seffill(**);
coute<setw(5)<<a<<setw(5)<<b<<endl;
cout<<setw(é)<<a<<setw($)<<b<<endl;

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

display of a floating point value. Setprecision (int p)

B write c++ program to use setprecision:


#include<iostream.h>
#include<iomanip.h> 1.7
void main( void) 1.66667
{
floata,b,c;
a=5; b=3; c=a/b;
seffill(**);
coute<setprecision(1)<<c<< endl;
cout<setprecision(5)<<c<< endl;
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?

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


it.

Qé: What is the main purpose of endland \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?

Q10: List the priorities of the arithmetic operations.

Q1 Find the value of A for the following:


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

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?

Ql4: Find the value of B {true or false) for the following:


i=5;
i=9
B=1((i>0)&& [i>=]));
Q15: Write C++ program to read x and compute sin, cos, and tan ofx.

Q16: Rewrite the equivalent statements for the following examples,


and find itresults. Assume: X=2, Y=3,7=4,V=12, C=8.

(X+=5, Y-=8, I*=5, V/=4, C %=3)

Q17: 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 < 0) AND (B/C <= 0).

Q18: Write a program in C++ to find the area of a circle.

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.

2. The Single lf_ Statewment Structure:


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

@ statementl

Example 1: if (awrg>=3.5)
cout << “good”;

Example 2: if (x>0.0)
sum += x;

Example 3: cin >> num;


if ([(num==0)
zcount = zcount + 1;
Q Write a C++ program to read any two numbers and
print the largest value of it:
#include<iostream.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. The Single Block I_f_ Statemeent 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 )
{
statement! ;
statement? ;
statement3 ;
1

= 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=0;
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)
statement! ; {statements }
else statement2; else {statements}

4. The tf/else Statement Structure:


The IF structure is

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

braces leads to confusion so:


If (i>j) { If (a>b)
temp=qa;
}
Else
temp=b;

Example 1: cin >> value;


if (value >=0)
cout << “positive”;
else
cout << “negative”;
Example 2: cin >> num1 >> num2;
if {(num1>num2)
cout << numl;
else
cout << num2;

B 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:
#include<iostream.h>
void main( )
{
int degree;
cin >> degree;
if (degree >=50)
cout << "pass”;
else
cout << “fail”;

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:

General Form of else if statement:

if ( expression or condition 1) statement! ;


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

&. Nested f Statements:


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}
}
,Q\ Write C++ program to find a largest value among three numbers:

#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

1. The Switeh Selection Statement (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 ( sefector)
{
case /abell : statementl; break;
case /abel2 . statement?; break;
case /abel3 : statement3; break;

case Jabel-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;
,Q\ Write C++ program to read integer number, and print the name of
the day in a week:
#include<iostream.h>
void main()
{
intday;
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 é: 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:
#include<iostream.h>
void main()
{
inta, b;
char x;

cout << “Enter iwo 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. Nested Switeh Selection Statement:


General Form of Nested Switch Selection statement:
switch ( sefector?)
{
case /abell : statementl; break;
case /abel? . statement?; break;
case /abel? : switch ( sefector2)
{
case /abell : statementl; break;
case /abel2 : statement?; 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)

case 1 : cout << “Software”; break;


case 2 : cout << “Information system”; break;
case3: cout << “Security”;
case4: cout << “Al";

default cout << “Invalid day number”; break;

3. conditional Statewent:

General Form of Conditional statement:

( condition? True : False)

Example 1: cin >> value;


cout << (value >= 07? “positive” : “negative” );

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

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

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

Q1 Write C++ program to read 5 numbers and determine if the numbers


sorted ascending or not.

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.

2. while g_p_@ti,tigw Structure:

while (condition )
statementd ;

while (condition )
{
statementd ;
statement2 ;

statement-n ;
¥

T
@ Statement 5

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


and a value returned by a function.

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
}

B write c++ program to find the summation of the following series:


sum=1+3+5+7+..+99
lin other words: find the summation of the odd numbers, between 0 and 100)

#include<iostream.h>
void main( )
{
int count=1;
intsum=0;
while ( count<=19% )
{
sum = sum + count;
count = count + 2;
}
cout << “sum is: “ << sum << endl;

B write c++ program to find the cub of a number, while it is positive:


#include<iostream.h>
void main( )
{
int num, cubenum;
cout << “Entfer 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
E 2212422492 40 an2
i=1
#include<iostream.h>
void main()
{
inti=1,n,sum=0;
cout << “enter positive number”;
cin>>n;
while (i<=n)
{
sum+= j¥j;
i++;

}
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®
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:

Qutput: even numbers only


02468
=10

while (i< 10)


Example 7
,Q\ 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 = 50, high = 70;
do
{
cout << “enter number: “;
cin >> x;
if ( x >=low && x<=high)
accept =1;
else
accept=0;
} ; -
while (1 accept); +————————¥{ wpie oo iem her
}

B wiite 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;
float av=0;
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 ¢
,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:

for ( initialization ; continuation condition ; update )


statementl ;

for ( initialization ; continuation condition ; update )


{
statementl ;
statement2 ;

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


cout << 012345678¢9

Example 2: for (i=0; i<10; i+=2) Qutput: sven nurmbers only


cout << j; 024468

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


only
cout << j; 1357%9

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

,Q\ Write C++ program to print the following:

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

2. More about For Statement:


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

M We can create infinite loop, as follow:


for(;:)
2. Nested Loops:
We can put loops one inside another to solve a certain programming
problems. Loops may be nested as follows:
loop1 Ioop1 loop1
loop2 loop2 loop2
|: loop3

loopa

B write c++ program to evaluate the following series:


5 10
i+2j
i=1 =1

12345678910 12345678910 12345670910 123456768910 12345678910

=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

1. Breaking Control Statements:


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

(a) Break Control Statewent:


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++)


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

Example 2: for {i=1; i<10; ++1)


for {j= ;<200 ++j)
{
cout << i*j<<endl
if {j==10) break;
}
Example 3: Switch (day) {
Case ‘1’:cout<<’Monday\n”;
Break;
Case '2': ...
}
Example 1
B write c++ program to check if zero or negative value found:

#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++
}
}

(b) Cowntinue Control Statements:


The continue is used to repeat the same operations once again even it it
checks the eror. 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 emor 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;
Pl
Example 1: Example 2:
do
{ n=1;
cin >> x; for(i=1;i<5; ++)
cin>> n; {
if(n<1) continue; cin>> x;
cout << x; n=5*x+t+ * (-1) /' n;
--n; if(n<1) continue;
} cout << n;
while(n<1); }

(c) aoto Statewent:

The goto statement is used to alter the program execution sequence


by transferring the control to some other part of the program. Its general

syntaxis: (goto label;)


There are two ways of using this statement:
1. Unconditional Goto: Itis used just to transfer the control from one part of

the programto the other part without checking any condition. It is


difficult in use.

Write C++ program to check if zero or negative value found:


#include<iostream.h>
void main( )
{
Start: coutg™**\n™:
Goto start;

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

Q1: And the summation of the numbers between 1 and 100.


for(i=1;i<=100; i++ ) i=1;
s=5+1; while (i <= 100)

s=s+i;
i

Q2: Find the factorial of n.


cin>>n; cin >> n;
ji<=n; i++) i=2; i=2;
f=f*i while (i<=n)

f=f*i
i++;

while (i <= n);

Q3: To find the result of the following:


for(i=1;i<=20;
i++) i=1;
s=s+ (i *i); while (i <= 20)

s =s+ (i *i); s=s+ (i *i);


o 7 i++;
3
while (i <= 20);

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.

for(i=1;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: Find the sum of the follol wings =1+3+5+7+.. +99.


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

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

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.


Forexample: 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:
inti;
i=12;
do
{
cout << i<< endl;

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

Using For Statement:


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

Q12: Write C++ program to print t e following figures:

WONONO W =T
woNvNG W

waNe W
nNe NG,
NG,

N
~Ne~

~e~
-

-
BN
BB EEE RN

e
(RN
FEE

PR R

BEE
W

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


e =1+ (1/11)+ (1/20) + (1/3) + ... + (1/nl)
Ql4: Write C++ program to find e from the following series:
e=T+x+e/2)+ (/3)+... @ /al)

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

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


for(; ;)
{
cout << “enter your number: “;
cin >> x;
if (x%2==0) continue;
if (x% 3==0) break;
cout << “Bottom of loop” << end|;
!
Q17: Whatis the output of the following C++ segment of code:
for (1=0;1<8;1++)
{
if{1%2==0) cout<<l+]1<<end]
else if (1%3==0) continue;
else if (1%5==0) break;
cout << “end program \n";
}
cout << “end ...";

Q18: Write C++ program to print the following figure:

Q19: Write C++ program to print the following searies:

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

other functions to perform various tasks. The main advantages of using a


function are:
« Easy to write a comect small function.

« Easy to read, write, and debug a function.

« Easier to maintain or modify such a function.


« Small functions tend to be self documenting and highly readable.
% It can be called any number of times in any place with different
parameters.

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:

void printmessage { ) int max (int a, int b)


{ {
cout << “University of Technology”; intc;
} ifla>b) c=a;
else c=b;
void main { ) return (c);
{ }
printmessage|( );
} void main ( )
{
cout << max (5, 6);
}
2. Return Statement:
The keyword return is used to terminate function and return a value to
its caller. The return statement may also be used to exit a function without
returing a value. The return statement may or may not include an expression.

Its general syntax is:


Return;
Return (expression);
The return statements terminate the execution of the function and pass the
control back to the calling environment.

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

Write a function to find the largest integer among three integers


entered by the userin the main function.

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

8 write program in C++, using function, presentation for logic gates


{AND, OR ,NAND, X-OR,NOT) by in A,B enter from user.

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

toid ORF(int a,int b)

cout<<(a| | b);

toid XORF(int a,int 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.

A-Passing b\u} value:

When parameters are passed by value, a copy of the parameters


value is taken from the calling function and passed to the called function. The
original variables inside the calling function, regardless of changes made by
the function to it are parameters will not change. All the pervious examples

used this method.

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:

1. A function is invoked without passing any formal argument from the

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

a program which return back a value to the calling environment.


Here are two programs that find the square of the number using and not
using a return statement.

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;

Cout<<"Enter a value for n?"<<endl:


Cin>>n;
Cout<<”Enter a value for x ?"<<end|;
Cin>>x;
1=3; sum=x; sign=1;
While (i<=n) {
Factval=fact(i);
Pow=power(x,i);
Sign=(-1)*sign;
Temp=sign*pow /ffactval;
Sum=sum+temp;
I=i+2;
}
Coute<”"sum of series ="<<sum;
}

Long int fact (int max)


{
Long intvalue;
Value=1;
For(int i=T;i<=max;++i)
Value=value*l;
Return (value);
}
Float power (float x, int n)
{
Float value2;
Valve2=1;
For(int j=1;j<=n;++j)
Valve2=value2*x;
Return(value2);
}
2. Actual and Formal Arguments:
The arguments may be classified under two groups, actual and formal

arguments:
(a)Actuadl arguments: An actual argument is a variable or an expression
contained in a function call that replaces the formal parameter which

is a part of the function declaration. Sometimes, a function may be


called by a portion of a program with some parameters and these
parameters are known as the actual arguments.

(b)Formal arguments: are the parameters present in a function definition


which may also be called as dummy arguments or the parametric
variables. When the function is invoked, the formal parameters are

replaced by the actual parameters. Formal arguments may be


declared by the same name or by different names in calling a portion
of the program or in a called function but the data types should b e

the same in both blocks


For example:
# include <iostream.h>
Void main()
{
Int x,y;
Void output (int x, int y); // function declaration

auipui (xy) // x and y are actual arguments

Void output (int g, int b) // forma or dummy arguments


{
// body of function
}

2. Local and global variables:


The variables in general bay be classified as local or global variables.
(a)Local variables: |dentifiers, variables and functions in a block are said to
belong to a particular block or function and these identifiers are known
as the local parameters or variables. Local variables are defined inside
a function block or a compound statement. For example,

Void func (int |, int j)

Int k,m; // local variables


...... // bodyofthe function

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

and each variable will be treated as a different entity.


(b)Global variables: these are variables defined outside the main function
block. These variables are referred by the same data type and by the

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.

There is a distinct difference between normal and recursive functions. A

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)

Void funcl(); //function declaration

Func1(); //function calling


}
Void func1() //funcfion definition
{

Func1(); //function calls recursively

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;

Int sum(int n) //recursive function


{
Int sum(int); //local function declaration
Int valve=0;
If (n==0)
Return (value);
Else
Value=n+sum(n-1);
Return (value);
}

The output of the above program:


Enter any integer number

Value = 11 and its sum=66


The following illustrations will be helpful to understand the recursive function
For value 1 For value 2 For value 3
=1+sum(1-1) =2+sum(2-1) =3+sum(3-1)
=140 =2+1+sum(1-1) =3+sum(2-1)
=1 =3 =3+2+1+sum(1-1)
=6

,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;

Long intfact (long int n) //recursive function

Long intfact(long int); //local function declaration


Int value =1;
If (n==1)
Return(value)
Else
{valve=n*fact(n-1);
Return(value);
b}
The oulput of the above program:
Enter any integer number

Value = § and its factorial=120


The following illustrations will be helpful to understand the recursive function
For value 1 For value 2 For value 3
=1*fact(1-1) =2*fact(2-1) =3*fact(3-1)
=1 =2*1 =3*2*fact(2-1)
=2 3*2*1
=6
WORK SHEET (5)
Functions

Ql: Write a C++ program, using function, to counts uppercase letter in a 20


letters entered by the userin the main program.

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.

Qs: Write a C++ program, using function, to calculate the factorial of an


integer entered by the user at the main program.

Q9: Write a C++ program, using function, to evaluate the following


equation:
_oxl-y
R
Q10: Write a C++ program, using function, to test the year if it's a leap or
not.
Note: use y%4==0 8& yZ100!1=0:y
% 400 ==

Q1 Write a C++ program, using function, to find Xy.

Note: use pow insfruction with math.hlibrary.

Ql12: Write C++ program, using function, to inverse an integer number:


For example: 765432 > 234567

Write C++ program, using function, to find the summation of student’s


Q13:
marks, and it’s average, assume the student have 8 marks.

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

can be user-defined types like structures and objects.

2. Arra owne Dimension:


It is a single variable specifies each array element. The declaration of
one dimensional arrays is:
General Form of 1D-Array:

data-type Array-name [ size];

Examples: int age [10];


int num [30];
float degree[5]:
char a[15];

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

same type only the values vary.


2. witializing Array Elements:
- The first element of amray age:
age [0] = 18;

- The last element of array age:


age [?] =19;

- All elements of aray age:


age [?]={18,17,18,18,19,20,17,18,19};

-intx[1={128,50,11,7,30,100,22};

-inty [10] ={8, 10,18, 15,0, 1,17, 22};

4. Accessing Array EBlements:


We access each array element by written name of amray, followed by
brackets delimiting a variable (or constant) in the brackets which are called
the array index.

- Accessing the first element of array num to variable x:


x = num [0]:
- Accessing the last element of aray num to variable y:
y = num [9];
- cout << num [0] + num [9];

-num [0] =num [1] + num[2];

-num [7] =num [7] + 3; € num [7]+=3;

5. Read / \Write / Process Arva Y Elewents:


- cout << num [4]; - for (int i=0; i<10; i++)
cout << numl[i];

-if (num [5] > 5) - for (int i=9; >=0; i++)


cout << “greater”; cout << num[i];

- for (int i=0; i<10; i++) - sum=0;


cin>>num[i]; for (int iF0; i<10; i++)
sum = sum+ numlil;
Example 1
B write C++ program to display 2nd and 5" elements of amray
distance:
#include<iostream.h>
void main( )
{
double distance[ ] ={23.14, 70.52, 104.08, 468.78, 6.28};
cout << “2nd element is: “ << distance[1] << endl;
cout << “5th element is: “ << distancel4];
}

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

cout << “The reverse order is: \n™;


for (i=4;i>=0;i--)
coutkg ik “ “g< a[i] << endl;

B write c++ program, to find the summation of array elements:


#include<iostream.h>
void main ( )
{
int const L = 10;
intalll;
intsum=0;
cout << "enter 10 numbers \n";
for (inti =0;i <L;i++)
{
cout << “enter value “<<i<< “:
cin>>alil;
sum+=ali];
}
cout << "sumis: " << sum << endl;
}

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;

B Write C++ program, to give the number of days in each month:

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

B write C++ program, using function, to find {search) X value in


amray, and return the index of it's location:

#include<iostream.h>

int search(int a[ ], inty)


{
int i=0;
while (a[i]!=y)
i++;
return (i );
}
void main ( )
{
int X, f;
int a[10]={18, 25, 36, 44, 12, 60, 75, 8%, 10,50 };
cout << “enter value to find it: “;
cin>> X;
f= search (a, X);
cout << “the value “ << X << “is found in location “<< f;
Example 7
Write C++ program, to split the odd numbers and even numbers of
one array into two amrays:
a=[1,2345678 ..,20]
aodd =[1,3, 5 L 19]
aeven=[2,4,6,8 ..,20)

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

General Form of 2D-Array:

data-type Array-name [ Row-size] [ Col-size ];

Examples: int a[10] [10];


int num [3] [4];
=1

£4
~

W
o
a

row | 110Ny

2. nitializing 2D-ArvaY Elements:


- The first element of aray age:
a2l [38]1={{1,23},{4,5 6}
2. Read / Write / Process Avm% Elewments

Q Write C++ program, to read 15 numbers, 5§ numbers per row, the


print them:
#include<iostream.h>
void main ()
{
ita[3][5]
inti,j;
for(i=0;i<3;i++)
for(j=0;j<5;j++)
cin>>alilljl;

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

0,0 10,1 |0,2 0,0

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.

Q2 Write a C++ program, using function, to compute the number of zeros


in the array.

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

Qs Write a C++ program, using function, to reads temperatures over the


30 days and calculate the average of them.

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

Ql3: Write C++ program, to read A[ n, n ] of character, then find array B


and array C, such that B contain only capital letters and C contain
only small letters.
Ql4: Write C++ program, to read A[ n, n ] of numbers, then put 10 instead
each even positive number.

Q18: Write C++ program, to read A[ n, n ] of numbers, then put 10 instead


each even positive number in the first diagonal.

Q16: Write C++ program, to read A[ n, n | of numbers, then find the


minimum number in array.

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.

mmd |3 23 |45| 7 |16|5 |10

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

Q25: Create the arrays bellow.

1111 2111
2222 1211
3 333 11 21
4 444 1T 11 2

You might also like