C++ and Programming Fundamentals

Download as pdf or txt
Download as pdf or txt
You are on page 1of 86

C/C++ and Programming

Fundamentals

Dr. garima Sinha 1


Computer
Computer is an electronics device which processes data to
make meaningful information.
Characteristics of computing devices
• Speed
• Accuracy
• Diligence
• Storage Capacity
Limitations of computing devices
• Lack of IQ
• No Emotions

Dr. garima Sinha 2


Components of Computing
• Input
• Process
devices
• Output
• Input Devices
Keyboard
Scanner
Optical Devices
OBR (Optical Barcode Reader)
OCR (Optical Character Reader)
MICR (Magnetic Ink Character Remarker/Recogniser)
Pointing Devices
Mouse
Joystick
Touch Screen Kiosk
Digital Pen
Digitizer
Microphone
Punch card Reader
Dr. garima Sinha 3
Output Devices
VDU (Visual Display Unit)
CRT (Cathode Ray Tube)
Monitor
Projector
LCD (Liquid Crystal Display)
Printer
Impact
DMP (Dot Matrix Printer)
Daisy Wheel, etc.
Non-impact

Inkjet, Laser printer, etc.


Plotter
Speaker

Dr. garima Sinha 4


Process
ALU (Arithmetical and Logical Unit)
CU (Control Unit)
MU (Memory Unit)
Memory Unit
Memory in computer in computer system is required for
information storage as well as its subsequent retrieval.
Types of Memory
Primary/Volatile/Central/Internal Memory
RAM (Random Access Memory)
ROM (Read Only Memory)
PROM, EPROM, EEPROM
Secondary/Permanent/External/Non-volatile Memory
Magnetic Tape, Magnetic Disk, HD/WD, FD, CD, DVD, Pen
Drive, Zip Drive, External Disk Devices.

Dr. garima Sinha 5


Basic Block Diagram of
Computers
ALU

Input CU Output

PM

SM

Dr. garima Sinha 6


Data Representation and Information Storage
• Any physical devices which stores data is a two state device, one
is its ON state and another is its OFF state. ON state is
represented by 1’s and OFF is by 0’s, the combination of 1’s and
0’s is called as Binary Digits (in short Bits).
• In Magnetic Memories the representation of ON and OFF is
represented by polarization of magnetic poles i.e. form N -> S
and S->N.

Combination of 8 bits is – 1
1024 byte - 1 KB
1024 KB - 1MB
1024 MB - 1GB
1024 GB - 1TB
Dr. garima Sinha 7
Operating System
• Computer System is quite sophisticated and very often a
user may unaware of its complete potential so an interface
is needed between computer hardware and user and this
interface is known as “Operating System”
• Functions of Operating System
Process Management
User Management
Time Management
Memory Management
I/O Management
Types of Operating System
Single User OS
Multi User OS
CUI
GUI
Desktop
Distributed
Dr. garima Sinha 8
Types of software
• System Software
• OS, Compilers, Interpreters, Firmware's etc.
• Application Software
– Packaged Software
• DBMS Oracle, FoxPro, MS-Access, SQL
• Office Automation MS-Office
• Financial Accounting Tally
• Web Browser Internet Explorer, Fireball, Mozilla
• Web Servers PWS, JWS, Apache, IIS
• Multimedia based software's
– Custom software

Dr. garima Sinha 9


Program
• Program :Program is set of logically related instruction given
to computer to solve a task in specified manner for desired
result.
• Programming : The art of writing program is called as
programming.
• Programming Language : The language through which we
instruct computers.

• Types of Programming language :


– Low Level Language
– Assembly level Language
– High level Language
– Fourth Generation Language

Dr. garima Sinha 10


• Sequential programming language
• Structured programming language
• Object Oriented programming structured
• Event Driven programming.

Dr. garima Sinha 11


Tools of Programming
• Flow Chart
• Pseudo code
• Algorithm

• Flow Chart : It is Graphical representation or pictorial view


of the program, it is very easy to use and understand the
stepwise solution of a problem.
As it is graphical representation of a program, so it
uses many graphical symbols to construct a flow diagram.

Symbols Meaning
Data Input/Output

Dr. garima Sinha 12


Process

Start/End

Decision

Connector

Directional Arrows

Pseudo Code (False Code): It is code which is not written in any


programming language rather it is written in any human
under stable Language like English, but it looks like
programming code so it is called as Pseudo code or False
code.
Dr. garima Sinha 13
• Algorithms : An Algorithm is any well-defined computational
procedure that takes some value, or set of values, as input
and produces some value, or set of values, as output.
An algorithm is thus a sequence of computational steps
that transform the input into the output.
We can also view an algorithm as a tool for solving a
well-specified computational problem.

For example, Sorting Problem

Input: A sequence of n numbers(a1, a2,….,an)


Output: A permutation (reordering) (a’1,a’2,….a’n) of the input
sequence such that a’1 <=,a’2 <=.a’n

For example, given the input sequence (31, 41, 59,26,41,58),


a sorting algorithm returns as output the sequence (26, 31,
41, 41, 58, 59.)
An algorithm is said to be Correct if, for every input
instance, it halts with the correct output.

Dr. garima Sinha 14


Number system and conversion method
• If we want to store decimal numbers in a computer and
perform arithmetic operations on them, the representation
must have a value assigned to the numbers. In order to do
this, we convert a decimal number to another number which
uses only the symbols “0” and “1” and has a value which is
equal to that of the given decimal number.
Consider, for example, the decimal number 4903. The
value of each digit in this number is determined by:
(1) The digit itself
(2) The position of the digit in the number
(3) The base or radix of the number system.
The base of a number system is defined as the number of
distinct symbols used to represent numbers in the system.
The decimal uses the ten symbols 0, 1,2,3,4,5,6,7,8 and 9
and its base is thus ten.

Dr. garima Sinha 15


• If a number system has only two symbols, then its base is 2.
Such a system is known as Binary System. The two symbols
used in the system, namely, 0 and 1 are binary digits or bits.
Numbers in this system are strings of bits. For example, a
binary number is shown below:
1 0 1 0 1

Most Significant Bit Least Significant Bit


The rightmost bit is called the least Significant bit and the
leftmost bit the most significant bit. The weights assigned
to bits in this system are powers of 2, namely 20=1, 21=2,
22=4 etc. In order to find the decimal value of a binary
number, we multiply its least significant bit by the weight 1,
the next bit to its left by 2 and so on. Thus the decimal
value of the binary number 10101 is calculated as shown
below
Dr. garima Sinha 16
1 0 1 0 1
1*24 + 0*23 + 1*22 + 0*21+ 1*20
16 + 0 + 4 + 0 + 1 =21

As another example the binary number 10010101 is converted to its


decimal equivalent as shown below:
(1*128)+(0*64)+(0*32)+(1*16)+(0*8)+(1*4)+(0*2)+(1*1)=149

Counting in the binary system is similar to that in decimal. In decimal


we start from 0, add a 1, obtain 1 and continue adding 1
successively till we reach 9. As the base of the system is ten,
there are no further symbols. Thus when we add 1 to 9 we
count 10. The 1 becomes the carry to the tens position in the
decimal system. Similarly we count 100 after reaching 99.
Counting in binary system is similar and proceeds as follows:
0, 1, 10, 11, 100, 101, 110, 111, 1000, 1001……………

Observe that we require 3 bits to represent decimal numbers 0 to 7


and 4 bits to represent 8 and 9. thus , on average
(8*3+2*4)/10=3.2 binary digits are required to represent a
decimal digits. Dr. garima Sinha 17
• 20 =1
• 21=2
• 210=1024 1K
• 211=2048 2K
• 220=1048576 1M
• 230=1073741824 1G

Representation of Fractions:
Decimal fractions are interpreted as follows:
0.235 = 2*10-1 + 3*10-2 + 5*10-3

Binary fractions are represented as follows:


0.1011 = 1*2-1 + 0*2-2 + 1*2-3 + 1*2-4
= ½ + 0 + 1/8 + 1/16
= 11/16 = 0.6875

Dr. garima Sinha 18


• C Fundamentals

The C Character Set


A to Z, a to z,
0 to 9
Special characters
! * + \ “ <
# ( = | { >
% ) ~ ; } /
^ - [ : , ?
& _ ] ‘ . (blank)

@ $ \b \n \t

Dr. garima Sinha 19


Identifiers and Keywords:
Identifiers are name given to various program elements,
such as Variables, functions and Arrays.
Identifiers consists of letters and digits, in any order,
except that the first character must be a letter.
Both upper and lowercase letters are permitted, though
common usages favors the use of lowercase letters for
most types of identifiers.
Identifiers and keywords are case sensitive.

Examples:
x y12 sum_1 _temerature
names area tax_rate TABLE
Invalid Examples:
4th “x” order-no error flag
*An identifier can be up to 31 character long.

Dr. garima Sinha 20


KEYWORDS
There are certain reserved words, called keywords, that
have standard, predefined meanings in C.
These keywords can be used only for their intended
purpose; they cannot be used as programmer-defined
identifiers.
Keywords:

auto break case char const


continue default do double else
enum extern float for goto
if int long register return
short signed size of static struct
switch typedef union unsigned void
volatile while

Dr. garima Sinha 21


Data types
Constant
Variables

Data Types

Numeric Non Numeric

Whole Number Real Number Character

Short int long float double char


2B 2B 4B 4B 8B 1B

Dr. garima Sinha 22


Constants :
Constants are data item whose value never get changed
while execution of program. C has four basic types of
constants.
1. Integer constants
2. Floating-point constants
3. Character constants
4. String Constants.

* commas and blank spaces cannot be included within the


constant.
* The constants can be preceded by (-) sign if desired.
* The value of constant cannot be exceed specified
minimum and maximum bounds.

Dr. garima Sinha 23


Integer Constants:
Valid integer constants:
0 1 743 5280 32767 9999
Invalid integer constants:
12,243 36.0 10 20 30 123-45-6789 0900

Constants Number System


50000U decimal (Unsigned)
123456789L decimal (Long)

Dr. garima Sinha 24


Constant Number system

123456789UL decimal (Unsigned Long)

Floating point constants:


0. 1. 0.2 827.602 5000. 0.000743

Character Constants
‘A’ ‘x’ ‘3’ ‘$’ ‘‘
String Constants:
“Amit” “2225378”

Dr. garima Sinha 25


Escape Sequences:
Certain nonprinting characters, as well as the double
quotes(“), the question mark (?) and the backslash(\) , can
be expressed in terms of Escape sequences.
An Escape sequence always begins with a backward slash
and is followed by one or special charter.

Character Escape Sequence ASCII Value


bell (alert) \a 007
backspace \b 008
horizontal tab \t 009
vertical tab \v 011
newline (linefeed) \n 010
carriage return \r 013
quotation mark \” 034

Dr. garima Sinha 26


Variable:
a variable is a data item whose value will change while
execution of program.

Declaration of variable:
A declaration associates a group of variable with a
specific data type.
All variable must be declared before they can appear in
executable statements.

Syntax;
Data type <variables names separated by comma>;

int a,b,c;
float d,e,f;
char star = ‘*’;

Dr. garima Sinha 27


Operators;
Mathematical
Relational
Equality
Logical
Text
Bit wise operator
Ternary Operator
Unary Operator

Mathematical +-*/%
Relational > < >= <= !=
Assignment =
Equality ==
Logical &&(AND) ||(OR) !(NOT)
Text +

Dr. garima Sinha 28


Bit Wise operator &|~
Ternary Operator (?:)
Unary operator --,++

Expressions:
It is combination of operator and operand, it may be of
following types:
1. Mathematical
2. Relational
3. Logical
4. Bit wise operator. Etc.

Dr. garima Sinha 29


Data Input and Output
Input Functions Output Functions
getchar() putchar()
gets() puts()

(cin cout)

Single character input:


getchar():
Syntax
Character variable=getchar();
Where character variable refers to some previously
declared character variable.
Single character output:
putchar(character varible);

Dr. garima Sinha 30


#include<stdio.h>
void main()
{
char letter[80];
int count, tag;
for(count=0; (letter[count]=getchar())!=‘\n’;++count) ;
tag=count;
for(count=0;count<tag;++count)
putchar(toupper(letter[count]));
}

Dr. garima Sinha 31


gets():
In case of gets(), the string will be entered from the
keyboard, and will terminate with a new line character.

char line[80];
gets(line)
puts(line)

wap in c++ to take name, marks of three subjects and give


their average.

Dr. garima Sinha 32


Storage Class
1. auto
2. extern
3. static
4. register

Dr. garima Sinha 33


Surprise Test
Q1. Which of the following are invalid variables name and why
BASICSALARY _basic basic-hra
#MEAN group. 422
population in 2006 over time mindovermatter
FLOAT hELLO queue
team’svictory Plot#3 2015_DDay
Q2. Point out the errors, if any, in the following C++
statements:
a) int – 314.562 * 150; b) name=‘Ajay’
c) varchar = ‘3’; d) 3.14 * r *r*h=vol_of_cyl;
e) k=(a*b)(c+(2.5a+b)(d+e)
f) si=p*r*t/100;
g) area=pi*r**2;
Q3. Evaluate the following expressions:
a) g=big/2+big*4/big-big+abc; abc=2.5, big=2
b) on=ink*act/2+3/2*act+2+tig ink=4, act=1, tig=3.2
Dr. garima Sinha 34
Q3. Convert the following equation into corresponding C++
statements.
a) R=2v+6.22(c+d)
g+v
Q4. What would be the output of the following programs:
a) void main()
{
int i=2, j=3, k, l;
float a,b;
k=i/j*j;
l=j/i*i;
a=i/j*j;
b=j=i*i;
cout<<k<<l<<a<<b;
}

Dr. garima Sinha 35


b) void main()
{
float a=5, b=2;
int c;
c=a%b;
cout<<c;
}
c) void main()
{
cout<<“nn\n\n nn\n”;
cout<<“nn/n/n nn/n”;
}
Q5. Pick up the correct alternative for each of the following:
a) C++ language has been developed by
(1) Ken Thompson (2) Dennis Ritchie
(3) Peter Norton (4) Martin Richard

Dr. garima Sinha 36


b) C/C++ can be used on
1) MS-DOS 2) Linux 3) windows 4) All
c) C/C++ programs are converted into machine language
with the help of
1) An Editor 2) A Compiler 3)An OS 4) None
d) The real constant in C++ can be expressed in which of
the following forms
1) Fractional form 2) Exponential form
3) ASCII form only 4) Both 1 and 2
e) A character variable can at a time store
1) 1 character 2) 8 character 3) 254 character4)None
f) The statement char ch=‘Z’ would store in ch
1) The character Z 2) ASCII value of Z
3) Z along with the single inverted commas
4) Both 1 and 2

Dr. garima Sinha 37


g) Which of the following is NOT a character constant
1) ‘Thank you’ 2) ‘Enter values of P, N, R’ 3)
’23.56E-03’ 4) All the above
h) The maximum value that an integer character constant can
have is
1) -32767 2) 32767 3) 1.7014e+38 4) All
i) A C/C++ variable cannot start with
1) An alphabet 2) A number 3) A special symbol
other than underscore 4) Both 2 & 3
j) Which of the following statement is wrong
1) mes=123.56; 2) con=‘T’ * ‘A’; 3) this=‘T’*20; 4) 3+a=b;
k) In b=6.6/a+2*n; which operation will be performed first/
1) 6.6/a 2) a+2 3) 2*n 4) Depends upon compiler
l) Which of the following is allowed in a C++ Arithmetic
instruction
1) [] 2) {} 3)() 4) None

Dr. garima Sinha 38


(m) Which of the following statements is FALSE
1) Each new C++ instruction has to be written on separate
line.
2) Usually all C++ statements are entered in small case
letters
3) Blank spaces may be inserted between two words in a
C++ statements.
4) Blank spaces cannot be inserted within a variable name.
(n) If a is an integer variable, a=5/2; will return a value
1) 2.5 2) 3 3) 2 4) 0
(o) The expression, a=7/22*(3.14+2)*3/5; evaluate to
1) 8.28 2) 6.28 3)3.14 4) 0
(p) Hierarchy decides which operator
1) is most important 2) is used first
3) is fastest 4) Operates on largest number.

Dr. garima Sinha 39


(q) In C++ a variable cannot contain
1) Blank spaces 2) Hyphen 3) Decimal Point 4) All
® Which of the following is FALSE in C/C++
1) Keywords can be used as variable names
2) Variable names can contain a digit.
3) Variable names do not contain a blank spaces.
4) capital letters can be used in variable names.
(s) In C++, Arithmetic instruction cannot contain
1) Variable 2) Constants
3) Variable names on the right side of =
4) constant on the left side of=
(t) Which of the following is odd one out
1) + 2) - 3) / 4) **
(u) What will be the value of d after operation d=2/7.0
1) 0 2) 0.2857 3) Cannot be determined
4) none

Dr. garima Sinha 40


Rule of Hierarchy of Operators
Rank Symbol Evaluation Rule
First () Evaluation expression enclosed
by parenthesis, innermost first.

Second Unary Operator Right to left among these unary


--, ++, typecast operators.

Third /, *, %

Fourth -, +

Last =, +=, *=, -=, /=, %=

Evaluate Expression -a * b/c + d % k – m/d * k + c

Dr. garima Sinha 41


Control Statements
1. if ()
2. if().. else
3. nested if()….else
4. Ternary Operator

1. if()
syntax
if (condition/conditions with the help of logical
operators)
{
Statement/Statements;
}

Dr. garima Sinha 42


2. if()
syntax
if (condition/conditions with the help of logical
operators)
{
Statement/Statements;
}
else
{
Statement/Statements;
}
WAP in c++ to compute greater number among two numbers.
#include<iostream.h>
#include<conio.h>
void main()
{
Clrscr();
Dr. garima Sinha 43
int a,b;
cout<<“Enter two numbers”;
cin>>a>>b;
if(a>b)
{
cout<<a<<”is greater then “<<b;
}
else
{
cout<<b<<”is greater then “<<a;
}
getch();
}

Dr. garima Sinha 44


Nested if …else

Syntax
if (condition/conditions)
{
statement/statements;
}
else{
if (condition/conditions)
{
statement/statements;
}
else
{
statement/statements;
}
}
Dr. garima Sinha 45
WAP in C++ to compute greatest among three numbers.
#include<iostream.h>
#include<conio.h>
void main()
{
Clrscr();
int a,b,c;
Cout<<“Enter three numbers”;
Cin>>a>>b>>c;
if(a>b)
{
if(a>c)
cout<<a;
else
cout<<c;
}
else
{
if(b>c)

Dr. garima Sinha 46


cout<<b;
else
cout<<c;
}
getch();
}
//largest among 3 numbers
#include<iostream.h>
void main()
{
int a,b,c,big;
cout<<“enter three numbers”);
cin>>a>>b>>c;
big=a;
if(b>big)
big=b;
if(c>big)
Dr. garima Sinha 47
big=c;
cout<<“The largest number is =”<<big;
}

Ternary operator(?:)
Max=(a>b && a>c ? a :((b>a && b>c) ? b : c)));

swith..case:
The swith..case is variation in the idea of nested if…else
against a single variable.
A switch statement is used when there is a choice as to
which code to execute, depending on the value of a
constant expression.
Different cases are presented, and are checked one by
one to see if one case matches the value of the constant
Expression. If case matches, its block of code is
executed .

Dr. garima Sinha 48


Syntax
switch (expression)
{
case value1: case value n:
{ {
statement 1; statement n;
break; break;
} }
case value2: default:
{ {
statement 2; default statement;
break; break;
} }
}

Dr. garima Sinha 49


Start

Input n

Case 1 default
Case 2Case n

Stmnt n default
Stmnt 1 Stmnt 2

stop

Dr. garima Sinha 50


WAP in C++ to print digits in words from 0 to 9.
#include<iostream.h>
#include<conio.h>
void main()
{
int n;
cout<<“Enter a number from 0 to 9”;
cin>>n;
switch(n)
{
case 1:
{
cout<<“\n One”);
break;
}
case 2:

Dr. garima Sinha 51


{
cout<<“\n Two”;
break;
}
….
case 9:
{
cout<<“\n Nine”;
break;
}
default:
{
cout<<“\n Value out of range”;
break;
}
}
getch();
Dr. garima Sinha 52
}
Q1. WAP in C++ to print RED if r/R is given as input BLUE if
b/B
And GREEN if g/G is given as input from keyboard.
Q2. WAP in C++ to print the upper most character as
A/B/C/D D
a/b/c/d d
0/1/2/3/4 4
Q3. WAP in C to calculate mathematical operations like this
Enter two nos
xy
*******Operations*******
1. (+)ADDITION
2. (-)SUBSTRACTION
3. (*)MULTIPLICATION
4. (/)DIVISION
Enter the operation(1 to 4)…?
The calculated result is : ……?
Dr. garima Sinha 53
Q4.WAP in C++ to compute name of month if number of month
is given as input.
Q5. WAP in C++to compute name of the day if no of day is
given as input.

Dr. garima Sinha 54


Q1. int x=3;
if(x==2);
x=0;
if(x==3)
x=x+1;
else
x=x+2;
what value will x contain when the sample code above is
executed?
a) 1 b) 2 c) 3 d) 4 e) 5

Dr. garima Sinha 55


Q3. int x=5;
int y=2;
Char op=‘*’;
switch(op)
{
default: x=x+1;
case ‘+’: x=x+1;
case ‘-’: x=x-y;
}
After the sample code above has been executed, what value
the variable x contain?
a) 4 b)5 c) 6 d) 7 e) 8

Dr. garima Sinha 56


Q4. int i=4;
switch(i)
{
default: case 8:
; i=i+5;
case 3: break;
i=i+5; }
if(i==8) cout<<i;
{ what will be the output of above
i=i+1; sample code?
if(i==9) 5 8 9 10
i=i*2; 18
}
i=i-4;
break;

Dr. garima Sinha 57


Q5. int i=4;
int x=6;
double z;
z=x/i;
cout<<z;
what will print, when the sample code above is executed/
a) z=0.00 b) z=1.00 c) z=1.50 d) z=2.00
e) z=NULL
Q6. int x=2*3+4*5; what will be the value of x after
execution?
a) 22 b) 26 c) 46 d) 50 e) 70

Dr. garima Sinha 58


Q8. int i=012, j=034, k=056;
cout<<i<<j<<k;
what would be the output?
a) 12/34/56 b)24/68/112 c) 3/28/46 d)
10/28/46
Q9. int i=1,j=1,n=1;
if(n>0)
i=i+1;
j=j+1;
cout<<i<<j;
a) 2 0 b) 1 1 c) 2 1 d) 2 2

Dr. garima Sinha 59


Looping / Iteration
The loop statement allows a set of instructions to be
performed repeatedly until a certain condition is fulfilled.
In C there are various ways to implement the looping
construct:
1. while loop
2. do while loop
3. for loop
1. The while loop keeps repeating an action until an
associated test returns false. This is useful where the
programmer does not know in advance how many times the
loop will be traversed.

Generally, a loop has four parts that have different


purposes:
1. Initialization 3. Increment/Decrement
2. Condition 4. Body of loop

Dr. garima Sinha 60


Initialization

False
Condition Exit

TRUE

Body of loop

Increment/decrement

Dr. garima Sinha 61


Syntax of while loop

initialization;
while (condition)
{
body of loop;
increment/decrement;
}
Wap in c++ to print 1 to 10 nos.

#include<iostream.h>
void main()
{
int i=1;

Dr. garima Sinha 62


if(i<=10)
if(i<=10)
cout<<i; cout<<i;
i=1+1; i=1+1;
if(i<=10) if(i<=10)
cout<<i; cout<<i;
i=1+1;
i=1+1;
if(i<=10)
if(i<=10) cout<<i;
cout<<i; i=1+1;
i=1+1; if(i<=10)
if(i<=10) cout<<i;
i=1+1;
cout<<i;
if(i<=10)
i=1+1; cout<<i;
if(i<=10) i=1+1;
cout<<i; }
i=1+1;

Dr. garima Sinha 63


#include<iostream.h>
void main()
{
int i;
i=1;
while(i<=10)
{
cout<<i;
i=i+1;
}
}

Wap to print 10 to 1.
Wap to print 1 to n
Wap to print n to 1

Dr. garima Sinha 64


Wap to print 1 3 5 7 …n.
Wap to print n….7 5 3 1
Wap to print 0 2 4 6 8 …n
Wap to print n 8 6 4 2 0
Wap to print table of a given no.
Wap to print factorial of a given number.
Wap to print reverse of a number.
Wap to sum of digits of a number
Wap to print sum of square of digits of a number.
Wap to print sum of cube of digits of a number and check
whether the number is armstrong or not.
Wap to find the sum of digits of a number reducing to one
digit.
Wap to swap two numbers.
Wap to swap two numbers without using third variable.
Wap to generate fibonacci series.

Dr. garima Sinha 65


( 2) for(;;) loop
The for loop is the simplest and the most commonly used
loop in C. This loop is frequently used, usually where the
loop will be traversed a fixed number of times.

Syntax:
for (initialization; condition; Increment/Decrement)
{
Body of loop;
}

Initialization; initialization;
while (condition) for (;condition;)
{ {
Body of loop; Body of loop;
Increment/Decrement; Increment/Decrement;
} }
Dr. garima Sinha 66
(3) do while loop

The do while loop is similar, but the test occurs after the
loop body is executed. This ensures that the loop body
will execute at once.

Syntax :

Initialization;
do
{
Body of loop;
}while (condition);

Dr. garima Sinha 67


#include<iostream.h>
void main()
{
int i;
i=9;
do
{
Cout<<i;
i=i+1;
}while(i<=1);
}

Dr. garima Sinha 68


Q1. int x=2*3+4*5, what will be value of x
a) 22 b) 26 c) 46 d) 50 e) 70

Q2. int x=0;


for (x=1;x<4;x++);
Cout<<x; What will be value of x printed.
a) 0 b) 1 c)3 d) 4 e) 5

Q3. x=3, counter=0;


while((x-1))
{
++counter;
x--;
}
a) 0 b) 1 c)2 d) 3 e) 4

Dr. garima Sinha 69


Nested Loop (Loop inside loop)
Initialization 1

Condn 1

Initialization2

Condn 2

Body of loop1 Body of loop2


I/D loop1 I/D loop2

Dr. garima Sinha 70


Syntax for nested loop:
for(;;)

for (initialization1;condn1;increment/decrement1)
{
for (initialization2;condn 2;increment/decrement2)
{
Body of inner loop (loop 2);
}
Body of outer loop (loop 1);
}

Dr. garima Sinha 71


Nested while loop

Initialization 1;
while(condition1)
{
initialization 2
while (condition 2)
{
body of loop 2;
increment/decrement 2;
}
Body of loop 1;
Increment/decrement 2;
}

Dr. garima Sinha 72


Q1. wap to print following pattern
A
AA
AAA
AAAA
AAAAA
Q2 WAP to print following
1
12
123
1234
12345

Dr. garima Sinha 73


Q3 wap to print following pattern
1
22
333
4444
55555

A
AB
ABC
ABCD
ABCDE

Dr. garima Sinha 74


Q4 WAP to print following pattern
*
**
***
****
*****

54321
4321
321
21
1

Dr. garima Sinha 75


55555
4444
333
22
1

*
**
***
****
*****
1
121
12321
1234321

Dr. garima Sinha 76


1234321
12321
121
1

*****
****
***
**
*

Dr. garima Sinha 77


*
**
***
****
*****
*****
****
***
**
*

Dr. garima Sinha 78


Break Control Statements:
With loops, break can be used to force an early exit from
the loop, or to implement a loop with a test to exit in the
middle of the loop body. A break within a loop should
always be Protected within an if statement which
provides the test to control the exit condition.

for example:
for (int i=0;i<=10;++i)
{
if (i==5)
break;
else
Takes control here
cout<<i;
}
cout<<“Hello”
}
Dr. garima Sinha 79
Continue Statement:
The continue statement is used to repeat the same
operations again even if it checks the error. The general
syntax of the continue statement is:
continue;

for example:
for (int i=0;i<=10;++i)
{ Takes Control here
if (i==5)
continue;
else
cout<<i;
}
cout<<“Hello”;
}

Dr. garima Sinha 80


Q1.int x=0;
for (x=1;x<4;x++);
Cout<<x;
What will be printed when the sample code above is executed?
a) x=0 b) x=1 c) x=3 d) x=4 e) x=5
Q2. In which type of loop, is the inner loop is executed
completely for every execution of the outer loop?
a) DO…WHILE b) IF c) Nested d) FOR
Q3. int a; a=0;
while (a++<3)
cout<<a;
a) a=0 b) a=1 c) a=2 d) a=3

Dr. garima Sinha 81


Arrays/Subscripted variable/Bounded Variable
When we declare arrays we declare
1. More than one variable
2. With the same name
3. Same data type
4. Same data length
5. And, in continuous memory location.

Arrays Declaration:
Data type arrays_name[index];

For example:
int a[5];
Memory representation:
a[0] a[1] a[2] a[3] a[4]

100 102 104 106 108


Dr. garima Sinha 82
Bounded variable:
Arrays are also known as bounded variable, as it is having
its boundary, which starts from 0 to size of arrays-1.
Subscripted variable:
Arrays are also known as subscripted variable as its every
elements are denoted by a subscript.
a[0],a[1],a[2],a[3],a[4], etc.
Memory addressing in an arrays:
address of an elements=base address + (index*size of
data type)
Address of the base element means address of the 0th
element.

For example address of a[3]


a[3]=100+(3*2)=106
Assigning value to an Arrays:
a[5]={10,20,30,40,50};
or
a[0]=10; a[1]=20; a[2]=30; a[3]=40; a[4]=50;

Dr. garima Sinha 83


Or
Cout<<a[0];
Cout<<a[1];
Cout<<a[2];
Cout<<a[3];
Cout<<a[4]);
Or
for(i=0;i<=4;++i)
{
Cout<<a[i]);
}

Wap in C++ to input ten numbers in an array and print it.


Wap in C++ to take ten numbers in an array and print its sum,
average and deviation;

Dr. garima Sinha 84


Wap in C++ to find greatest number in an array.
Wap in C++ to find smallest number in an array.
Wap in C++ to print the required number of element in an
array.
Wap in C++ to sort an array in ascending order.

Dr. garima Sinha 85


WAP In C++ to sort an array of string

Dr. garima Sinha 86

You might also like