0% found this document useful (0 votes)
40 views40 pages

Unit 2.6 For, Do, While Loop

The document discusses loops in C++ programming, including for loops, while loops, and do-while loops. It provides examples of using for loops to iterate through a range of numbers and print their values. It also demonstrates using a while loop to iterate from 1 to a given number N and print each value. Examples are provided to calculate the sum of the first N natural numbers and to check if a given number is prime.

Uploaded by

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

Unit 2.6 For, Do, While Loop

The document discusses loops in C++ programming, including for loops, while loops, and do-while loops. It provides examples of using for loops to iterate through a range of numbers and print their values. It also demonstrates using a while loop to iterate from 1 to a given number N and print each value. Examples are provided to calculate the sum of the first N natural numbers and to check if a given number is prime.

Uploaded by

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

COMPUTER PROGRAMMING (OBJECT ORIENTED

PROGRAMMING)
UNIT-2
By
ADITYA BHARDWAJ

• Email: [email protected] • https://www.researchgate.net/profi


le/Aditya_Bhardwaj

1
LOOPS
• There are three kinds of loops in C++: the for loop, the while
loop, and the do while loop.
1. For Loop Introduction
Loops in C++
Loops are the iterative Body
statements which are used Statement; of loop
to repeatedly execute a set
of instructions till a
condition is met. True

Loop
Condition? Condition

False
For Loop in C++
For loop in C++ looks like the following :
for (initialization; loop condition; increment/decrement)
Statement/Block_statement;

The statements inside the for loop are called the body of the loop and
will be executed till the loop condition is true.

Let us understand for loops using the following example:


for (i = 0; i < 2; i++)
cout << i << endl;
For Loop in C++ i = 0;

False
i < 2?
for (i = 0; i < 2; i++)
cout << i << endl; True

cout << i << endl;

i++;
Tracing the loop
So to find out what the output of our small loop will be, we will trace the
execution of the loop :

for (i = 0; i < 2; i++) 102 i


cout << i << endl;

Output :
Hence after the loop exits, the value of variable i is 0
2 and we have the output as shown. 1
For Loop in C++
for (initialization_expression; loop_condition; update_expression)
Statement/Block_statement;

1. The initialization_expression is evaluated first and is used to assign initial


values to our loop variables.
2. Next, our loop_condition is evaluated. If the loop_condition evaluates to
False, then we skip to the statement following the loop.
3. If the loop_condition evaluates to True, we execute the statements in the
body of the loop.
4. After that, we execute the update_expression which updates the value of
our loop variables
5. Next we return to step 3.
#include <iostream>
Example- 1 using namespace std;
int main() {
int i;
What will be the output of
this program? for (i = 2; i <= 20; i = i + 2)
cout << i << endl;
return 0;
}
#include <iostream.h>
Solution using namespace std;
int main()
{
Iteration 1: int i;
i has value 2 and we get 2 in for (i = 2; i <= 20; i = i + 2)
the output
cout << i << endl;
Iteration 2 : return 0;
i has value 4 and we get 4 in }
the output
#include <iostream.h>
Solution using namespace std;
int main()
Iteration 10: {
i has value 20 and we get 20 int i;
in the output
for (i = 2; i <= 20; i = i + 2)
Iteration 11 : cout << i << endl;
i has value 22 and the return 0;
condition fails
}
Thus the loop breaks and we
jump to next statement.
#include <iostream.h>
Solution using namespace std;
int main()
Output : {
2
4 int i;
6 for (i = 2; i <= 20; i = i + 2)
8 cout << i << endl;
10
12 return 0;
14 }
16
18
20
Exercise-2

Write a program which takes a natural number (say, N) as


input and finds the sum of first N natural numbers.

For example,
Input : 5 Output : 15
Input : 3 Output : 6
Solution Scheme
 Say the value of N is 5, so we have to compute the sum
(1 + 2 + 3 + 4 + 5)
 One method is to have two variables sum and count.
The variable count iterates from 1 to N and we keep
adding count to sum.
 So we can write a for loop for doing that…
Solution Scheme
int count, sum, N;
cin >> N;
Note the for (count = 1; count <= N; count++)
block {
statement sum = sum + count;
}
#include <iostream>
using namespace std;
Solution
Note : We generally declare
all our variables at the top
int main()
{ int count, sum, N;
cout << "Enter N : ";
cin >> N;
The following is the main sum = 0;
logic of the program :
for (count = 1; count <= N; count++)
{
sum = sum + count;
}
cout << "Sum is : " << sum;
return 0;
A new shorthand operator : +=
Very often in programming, we need to write expressions like :
number = number + 5;

There is an operator in C++ specifically for such operations.


So the above statement can be written as :
number += 5;

Similarly we can use the operators : -=, *=, /=, %=


number *= x ; // Same as number = number * x
Example -5 for Quiz int main()
Predict the output/error {
int x;
for(x=1;x<=3; x++)
{
cout<<x;
}
}

output: 123
Example -3 Practice Yourself

Write a program which takes a natural number (say, N) as


input and finds N! (factorial of N).

For example,
Input : 4 Output : 24
Input : 5 Output : 120
#include <iostream.h>
using namespace std;
Solution int main()
{
int count, fact, N;
cout << "Enter N : ";
The following is the main cin >> N;
logic of the program : fact = 1;
for (count = 1; count <= N; count++)
{
fact = fact * count;
}
cout << "Factorial is : " << fact;
return 0; }
2. While Loop
While loop
The syntax for while loop :
Variable Initialization
while (condition expression)
increment/decrement /
statements; Body of loop

The body of the loop is repeatedly executed as long as the expression


evaluates to True. For example :

int i = 0;
while (i < 10)
i++;
Example

Write a program which takes a natural number (say, N) as


input and prints all natural numbers from 1 to N.

For example,
Input : 5 Output : 1 2 3 4 5
Input : 3 Output : 1 2 3
Solution
int i, N;
The following is the main cin >> N;
logic of the program :
i = 1;
while (i <= N)
Note that for while loops,
we initialize the loop {
variable outside the loop cout << i << " ";
and update it inside
i++;
}
Find Output int i, N;
N = 5;
i = 1;
while (i <= N)
{
cout << i << " ";
i += 2;
}
cout << i << " ";
Find Output int i, N;
N = 5;
i = 1;
357
1 i while (i <= N)
{
cout << i << " ";
i += 2;
Output : 1 3 5 7
}
cout << i << " ";
Example
Write a program which takes a natural number (say, N) as input such
that N > 1, and checks if it is prime.

Definition : A prime number is a natural number greater than 1 that


has no positive divisors other than 1 and itself.
(Source: https://brilliant.org/wiki/prime-numbers/)

For example,
Input : 5 Output : Prime
Input : 9 Output : Not Prime
Solution Scheme
We keep a counter i which iterates from 2 to (N-1)

Each time we divide variable N by i and see if the remainder is 0

If yes, we have found a perfect divisor for N between [2, N-1], hence
the number is not prime

If no such i is found, the number is prime


int i, isPrime, N;
cin >> N;
Solution i = 2;
isPrime = 1;
while (( i < N ) && ( isPrime == 1 ))
{

The following is the main if (( N % i ) == 0 )


logic of the program : isPrime = 0;
i++;
isPrime = 1 means we have }
not found any i yet which if (isPrime == 1)
perfectly divides N. cout << "Prime";
else
cout << "Not Prime";
Exercise
Write a program which takes two natural numbers (say, X
and N, in that order) as input and finds the sum of
following series:
X + X2 + X3 + X4 + … + XN
For example,
Input : 3 2 Output : 12
Input : 5 3 Output : 155
3. Do-while Loop
Do-while loop

• The do-while loop is similar


to the while loop, except
that the test condition occurs
at the end of the loop.

• Having the test condition at


the end, guarantees that the
body of the loop always
executes at least one time.
Do-While loop
The syntax for do-while loop :
do
{
Statement ;
Body of loop Increment/decrement
} while ( loop condition ) ;

The loop condition is evaluated after executing the body of the loop,
hence the loop will run at-least once
int main()
Find Output {
int count = 10;
do
{
cout << count << " ";
count -= 2;
} while ( count > 0 );
return 0;
}
int main()
Find Output {
int count = 10;
do
{
Output : cout << count << " ";
10 8 6 4 2
count -= 2;
} while ( count > 0 );
return 0;
}
int main()
Example {
int number;
do
{
Think what the following
program will do? cout << "Enter a positive integer : ";
cin >> number;
} while ( number < 0 );
cout << "Number = " << number;
return 0;
}
int main()
Example {
int number;
This program will keep on do
reading the input from user
till it reads a positive integer {
cout << "Enter a positive integer : ";
This is an interesting
application of loops cin >> number;
} while ( number < 0 );
The concept used is that
body of do-while loop will be cout << "Number = " << number;
executed at least once before return 0;
testing the condition
}
{
int N = 4;
Exercise int i, j;
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
What will be the output
of this program? {
cout << j;
}
cout << endl;
}
}
/*The following program fragment is an input routine that insists that the user type a correct
response -- in this case, a small case ‘y’ or capital case 'Y'. The do-while loop guarantees that the
body of the loop (the question) will always execute at least one time.*/

#include <iostream>
using namespace std;

int main()
{
char ans;
do
{
cout<<"Do you want to continue (Y/N)?\n";
cout<< "You must type a 'Y' or an 'N'.\n";
cin >> ans;
} while((ans =='Y')|| (ans =='y'));
}

/*the loop continues until the user enters the correct response*/

You might also like