Week 07
Week 07
COMPUTER PROGRAMMING
Muzammil Ahmad Khan
[email protected]
2
Introduction of Nested Loop in C++
• A loop within another loop is called a nested loop. Nested loop means a loop
statement inside another loop statement. That's why nested loop are also called
as loop inside loop.
Working of Nested Loop
• Execution of statement within the loop flows in a way that the inner loop of
the nested loop gets declared, initialized and then incremented.
• Once all the condition within the inner loop gets satisfied and becomes true it
moves for the search of the outer loop. It is often called a loop within a loop.
3
Let's take an example:-
4
Example 1: C++ Nested for loop
// C++ program to display 7 days a weeks
#include <iostream>
using namespace std;
int main() {
int weeks = 3, days_in_week = 7;
for (int i = 1; i <= weeks; ++i) {
cout << "Week: " << i << endl;
5
Example 1: C++ Nested for loop
// C++ program to display 7 days a weeks Output
#include <iostream>
using namespace std; We can create nested
int main() { loops with while and
int weeks = 3, days_in_week = 7; do...while in a similar
way.
for (int i = 1; i <= weeks; ++i) {
cout << "Week: " << i << endl;
6
Nested for Loop
• A for loop within another for loop is • Nested while Loop
called Nested For loop • A while loop within another while loop
• The syntax of nested for loop is: is called Nested while loop.
• The syntax of nested while loop is:
for (initialization; condition; update) {
while (condition) {
for (initialization; condition; update)
while (condition) {
{
// body of inner while-loop
// body of inner for-loop }
} // body of outer while-loop
// body of outer for-loop }
}
7
Nested do-while Loop
• A do-while loop within another do-while loop is called Nested do-while loop.
• The syntax of nested do-while loop is:
do {
do{
// body of inner do-while-loop
}
while (condition);
// body of outer do-while-loop
}
while (condition);
8
Example 2: Displaying a Pattern
// C++ program to display a for (i = 1; i <= n; i++)
triangular pattern {
// Number is entered by the user
for (j = 1; j <= i; j++)
#include <iostream> {
using namespace std; cout << "* ";
}
int main() { cout << endl;
}
int i, j, n;
cout << "Enter Number : ";
return 0;
cin >> n;
}
9
Example 3: C++ Nested while Loop
// C++ program to display a while (i <= rows) {
triangular pattern of numbers using int j = 1;
nested while loop
while(j <= i) {
#include <iostream> cout << i;
using namespace std; j++;
}
int main() { cout << "\n";
i++;
int rows, i = 1;
cout << "Enter the number of rows: }
"; return 0;
cin >> rows; }
10
Output
Enter the number of rows: 4 • In this program, the outer loop
iterates from 1 to rows.
1
22
• The inner loop iterates from 1
333
to i. Inside the inner loop, we
4444 print the numbers.
11
C++ Nested do-while Loop
#include <iostream> }
using namespace std; while(c <= 5);
r++;
int main()
{ cout << "\n";
int r , c; }
r = 1; while(r <= 5);
do {
c = r;
do{ return 0;
cout << “*”; }
c++; 12
Output
*****
****
***
**
*
13
Example 4: C++ Nested do-while Loop
// C++ program to display a do {
triangular pattern of numbers using j = 1;
nested do-while loop do{
cout << j;
#include <iostream>
using namespace std; j++;
}while(j <= i);
int main() { cout << "\n";
i++;
int rows, i,j; }while(i <= rows);
i = 1;
cout << "Enter the number of rows: "; return 0;
cin >> rows; }
14
Output
15
break and continue Inside Nested Loops
• When we use a break statement inside for (int i = 1; i <= weeks; ++i)
the inner loop, it terminates the inner {
loop but not the outer loop. For cout << "Week: " << i << endl;
example, for (int j = 1; j <= days_in_week; ++j) {
// break during the 2nd week
// C++ program to display a triangular if (i == 2) {
pattern of numbers using nested do-while
loop break;
}
#include <iostream> cout << " Day:" << j << endl;
using namespace std; }
}
int main() { return 0;
int weeks = 3, days_in_week = 2; }
16
Output
Week: 1 • This program does not run the
Day:1 inner loop when the value of i
Day:2 is 2 i.e. it does not print the
Week: 2 days of the 2nd week.
Week: 3 • The outer loop that prints the
Day:1 weeks is unaffected.
Day:2
17
break and continue Inside Nested Loops
// C++ program to display a triangular pattern
• Similarly, when we use a
of numbers using nested do-while loop
continue statement inside the
inner loop, it skips the current #include <iostream>
iteration of the inner loop using namespace std;
only. The outer loop is
unaffected. int main() {
• For example int weeks = 3, days_in_week = 7;
18
break and continue Inside Nested Loops
for (int j = 1; j <= days_in_week; Output
Week: 1 • This program prints only
++j) {
Day:1 those days that are odd.
// continue if the day is an even
Day:3
number
Day:5 • Whenever the
Day:7
if (j % 2 == 0) { Week: 2
days_in_week is even, the
continue; Day:1 continue statement skips
} Day:3 that iteration of the inner
Day:5 loop.
cout << " Day:" << j << endl;
Day:7
} Week: 3
} Day:1
return 0; Day:3
} Day:5
Day:7
19
Nested Control Structures
• Suppose we want to create the following pattern
*
**
***
****
*****
• In the first line, we want to print one star, in the second
line two stars and so on
20
Nested Control Structures
• Since five lines are to be printed, we start with the
following for statement
for (i = 1; i <= 5 ; i++)
• The value of i in the first iteration is 1, in the second
iteration it is 2, and so on
• Can use the value of i as limit condition in another for
loop nested within this loop to control the number of stars
in a line
21
Nested Control Structures
• The syntax is:
for (i = 1; i <= 5 ; i++)
{
for (j = 1; j <= i; j++)
cout << "*";
cout << endl;
}
22
Nested Control Structures
• What pattern does the code produce if we replace the first for statement
with the following?
for (i = 5; i >= 1; i--)
• Answer:
*****
****
***
**
*
23
Summary
• C++ has three looping (repetition) structures: while, for, and
do…while
• while, for, and do are reserved words
• while and for loops are called pre-test loops
• do...while loop is called a post-test loop
• while and for may not execute at all, but do...while always
executes at least once
24
Summary
• while: expression is the decision maker, and the statement is the
body of the loop
• In a counter-controlled while loop,
− Initialize counter before loop
− Body must contain a statement that changes the value of the counter variable
• A sentinel-controlled while loop uses a sentinel to control the
while loop
25
Summary
• for loop: simplifies the writing of a count-controlled
while loop
• Executing a break statement in the body of a loop
immediately terminates the loop
• Executing a continue statement in the body of a loop
skips to the next iteration
• After a continue statement executes in a for loop, the
update statement is the next statement executed
26
Arrays
• An array is a collection (or group) of memory
locations, each having the same data type and the same
name.
27
Single-dimensional Arrays
• Has only a single subscript.
• E.g., array type float:
float expenses[5];
28
Single-dimensional Arrays
• The position number contained within square
brackets is more formally called a subscript
• A subscript must be an integer or an integer
expression
• E.g.,
int number[9];
29
Array Declaration
• Specified the type, name, and size of the array so that
the computer may reserve the appropriate amount of
data.
• To tell the computer to reserve 8 elements for integer
array score.
int score[8]; //consists of 8 elements
30
Array Declaration
31
Array Declaration
E.g.,
int a[10]; //declaration of variable with array
float expenses[10];
expenses[1] = 89.95;
expenses[4] = expenses[1];
#define MONTHS 12
int array[MONTHS]; //same as int array[12];
32
Initializing Arrays
• The elements of an array can be initialized in the array
declaration.
E.g.,
int array[4] = { 100, 200, 300, 400 };
• Others example
int scores[7] = {100,73,8,84,40,97,20};
33
Initializing Arrays
• You do not have to put in all the values
• If there are fewer initializers than elements in the array, the
remaining elements are automatically initialized to zero
int scores[7] = {100,73,8};
34
Initializing Arrays
• char grade[4] = {'A','B','C’};
• If the array size is omitted, the compiler creates an array just large
enough to hold the initialization values.
36
Program initializing an array with a declaration
#include<iostream>
using namespace std;
main()
{
int i;
int n[10]={32, 27, 64, 18, 95, 14, 90, 70, 60, 37};
for(i=0;i<=9;i++) // print array
cout<< n[i]<<endl;
return 0;
}
37
Program initializing an array with a declaration
Output
32
27
64
18
95
14
90
70
60
37
38
Program initializing an array with a declaration
#include <iostream> for (ctr = 0; ctr <= 11; ctr++)
using namespace std; {
int ctr; cout<<"Month"<< ctr
float expenses[12]; <<"="<<expenses[ctr]<<endl;
int main() }
{ return 0;
for (ctr = 0; ctr <= 11; ctr++) }
{
cout<<"Enter expenses for
month"<<ctr+1<<" : " ;
cin>>expenses[ctr];
}
39
Program initializing an array with a declaration
output
Enter expenses for month1 : 50 Month0=50
Enter expenses for month2 : 25 Month1=25
Enter expenses for month3 : 66 Month2=66
Enter expenses for month4 : 65 Month3=65
Enter expenses for month5 : 76 Month4=76
Enter expenses for month6 : 54 Month5=54
Enter expenses for month7 : 53 Month6=53
Enter expenses for month8 : 21 Month7=21
Enter expenses for month9 : 22 Month8=22
Enter expenses for month10 : 11 Month9=11
Enter expenses for month11 : 21 Month10=21
Enter expenses for month12 : 09 Month11=9
40
setw() manipulator
Output:
test 123
exam 234
result 789
43
setw() manipulator
• The setw can be used to ensure that the string read into
word does not exceed the size of array
• E.g.,
cin >> setw(20) >> word;
//specifies that cin should read a maximum of
19 characters into word and save the 20th location to
store ‘\0’
44
setw() manipulator
45
setw() manipulator
#include <iostream>
#include <iomanip>
using namespace std;
int main (void)
{
int a , b; a = 200; b = 300;
cout << a << b << endl;
cout << setw (5) << a << setw (5) << b << endl;
cout << setw (10) << a << setw (10) << b << endl;
return 0;
} 46