0% found this document useful (0 votes)
55 views38 pages

ch5 C++

This document summarizes chapter 5 of a C++ programming textbook. It discusses various loop structures in C++ like while, do-while, and for loops. It provides examples of using increment/decrement operators, counters, letting users control loops, and deciding which loop to use for different situations. It also covers nested loops and random number generation. Key topics include initializing and updating variables in for loops, pre-test and post-test loops, and using loops to repeat operations a known number of times.

Uploaded by

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

ch5 C++

This document summarizes chapter 5 of a C++ programming textbook. It discusses various loop structures in C++ like while, do-while, and for loops. It provides examples of using increment/decrement operators, counters, letting users control loops, and deciding which loop to use for different situations. It also covers nested loops and random number generation. Key topics include initializing and updating variables in for loops, pre-test and post-test loops, and using loops to repeat operations a known number of times.

Uploaded by

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

Chapter 5

Looping
Namiq Sultan
University of Duhok
Department of Electrical and Computer Engineerin

Reference: Starting Out with C++, Tony Gaddis, 2nd Ed.

C++ Programming, Namiq Sultan 1


5.1 The Increment and Decrement Operators

• ++ and -- are operators that add and subtract one from their
operands.

num = num + 1;
num += 1;
num++;

C++ Programming, Namiq Sultan 2


Program 5-1
// This program demonstrates the increment and decrement operators.
 int main()
{
int bigVal = 10, smallVal = 1;
  cout << "bigVal is " << bigVal << " and smallVal is " << smallVal << endl;
smallVal++;
bigVal--;
cout << "bigVal is " << bigVal << " and smallVal is " << smallVal << endl;
++smallVal;
--bigVal;
cout << "bigVal is " << bigVal << " and smallVal is " << smallVal << endl;
return 0;
}

C++ Programming, Namiq Sultan 3


Program Output

bigVal is 10 and smallVal is 1


bigVal is 9 and smallVal is 2
bigVal is 8 and smallVal is 3

C++ Programming, Namiq Sultan 4


Program 5-2
//prefix and postfix modes of the increment and decrement operators.
int main()
{
int bigVal = 10, smallVal = 1;
  cout << "bigVal starts as " << bigVal;
cout << " and smallVal starts as " << smallVal << endl;
cout << "bigVal--: " << bigVal-- << endl;
cout << "smallVal++: " << smallVal++ << endl;
cout << "Now bigVal is: " << bigVal << endl;
cout << "Now smallVal is: " << smallVal << endl;
cout << "--bigVal: " << --bigVal << endl;
cout << "++smallVal: " << ++smallVal << endl;
return 0;
}

C++ Programming, Namiq Sultan 5


Program Output

bigVal starts as 10 and smallVal starts as 1


bigVal--: 10
smallVal++: 1
Now bigVal is: 9
Now smallVal is: 2
--bigVal: 8
++smallVal: 3

C++ Programming, Namiq Sultan 6


Using ++ and -- in Mathematical Expressions

a = 2;
b = 5;
c = a * b++;
cout << a << " " << b << " " << c;

Results: 2 6 10

C++ Programming, Namiq Sultan 7


Using ++ and -- in Relational Expressions

x = 10;
if ( x++ > 10)
cout << "x is greater than 10.\n";

• Two operations are happening:


• the value in x is tested to determine if it is greater than 10
• then x is incremented

C++ Programming, Namiq Sultan 8


5.2 Introduction to Loops - The while Loop
• A loop is part of a program that
repeats.
• A while loop is a "pre test" loop - the
expression is tested before the loop is
executed

Initialize control variable


while(expression)
{
statement;
statement;
...
}

C++ Programming, Namiq Sultan 9


Program 5-3
// This program demonstrates a simple while loop.
void main()
{
int number;
 
cout << "This program will print numbers from 0 to 99:\n";
number = 0;
while (number <= 99){
cout << number << endl;
number++;
}
return 0;
}

C++ Programming, Namiq Sultan 10


Program Output with Example Input

This program will print numbers from 0 to 99:


0
1
2
3
4
.
.
99

C++ Programming, Namiq Sultan 11


Terminating a Loop

• A loop that does not have a way of stopping is called an


infinite loop
int test = 0;
while (test < 10)
cout << "Hello\n";

• A null statement is also an infinite loop, but it does nothing


forever:
while (test < 10);

C++ Programming, Namiq Sultan 12


5.3 Counters

• A counter is a variable that is incremented or decremented


each time a loop iterates.

C++ Programming, Namiq Sultan 13


Program 5-4

// This program displays the numbers 1 through 10 and their squares.


int main()
{
int num = 1; // Initialize counter
cout << "number number Squared\n";
cout << "--------------------------------------\n";
while (num <= 10) // Test counter
{
cout << num << "\t\t" << (num * num) << endl;
num++; // Increment counter
}
return 0;
}
C++ Programming, Namiq Sultan 14
Program Output

number number Squared


----------------------------
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
10 100

C++ Programming, Namiq Sultan 15


5.4 Letting the User Control the Loop

• We can let the user indicate the number of times a loop


should repeat.

C++ Programming, Namiq Sultan 16


Program 5-6
// This program averages a set of test scores for multiple students.
void main()
{
int numStudents, count = 0;
int score1, score2, score3;
float average;

  cout << "How many students do you have test scores for? ";
cin >> numStudents;
cout << "Enter the scores for each of the students.\n";

C++ Programming, Namiq Sultan 17


while (count++ < numStudents)
{
cout << "\nStudent " << count << ": ";
cin >> score1 >> score2 >> score3;
average = (score1 + score2 + score3) / 3.0;
cout << "The average is " << average << ".\n";
}
return 0;
}

C++ Programming, Namiq Sultan 18


Program Output with Example Input
This program will give you the average of three test scores per student.
How many students do you have test scores for? 3 [Enter]
Enter the scores for each of the students.

Student 1: 75 80 82 [Enter]
The average is 79.

Student 2: 85 85 90 [Enter]
The average is 86.67.
 
Student 3: 60 75 88 [Enter]
The average is 74.33.

C++ Programming, Namiq Sultan 19


5.7 The do-while Loop and for Loops
• A do-while loop is similar to a while loop, but in post-test format.
• This means do-while always performs at least one iteration, even
if the test expression is false from the start.

do{
statement;
Statement(s)
statement;
. . .
expn
}while(expression); True
False

C++ Programming, Namiq Sultan 20


Program 5-9
//This program repeats as many times as the user wishes
int main()
{
int score1, score2, score3;
float average;
char again;
do {
cout << "Enter 3 scores and I will average them: ";
cin >> score1 >> score2 >> score3;
average = (score1 + score2 + score3) / 3.0;
cout << "The average is " << average << ".\n";
cout << "Do you want to average another set? (Y/N) ";
cin >> again;
} while (again == 'Y' || again == 'y');
return 0;
} C++ Programming, Namiq Sultan 21
 Program Output with Example Input

Enter 3 scores and I will average them: 80 90 70 [Enter]

The average is 80.

Do you want to average another set? (Y/N) y [Enter]

Enter 3 scores and I will average them: 60 75 88 [Enter]

The average is 74.333336.

Do you want to average another set? (Y/N) n [Enter]

C++ Programming, Namiq Sultan 22


The for Loop

• Ideal for situations that require a counter because it has


built-in expressions that initialize and update variables.

for (initialization; test; update)


statement;

C++ Programming, Namiq Sultan 23


Program 5-11

// This program displays the numbers 1 through 10 and their squares.


int main()
{
int num;
 
cout << "Number Number Squared\n";
cout << "--------------------------------------\n";
 
for (num = 1; num <= 10; num++)
cout << num << "\t\t" << (num * num) << endl;
return 0;
}

C++ Programming, Namiq Sultan 24


Program Output

Number Number Squared


-------------------------
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
10 100

C++ Programming, Namiq Sultan 25


5.8 Deciding Which Loop to Use
• The while Loop
• A pre-test loop.
• Use when you do not want the loop to iterate if the condition is false
from the beginning.
• Ideal if you want to use a sentinel (see problem 5 slide 37).
• The do-while Loop
• A post-test loop.
• Use if you always want the loop to iterate at least once.
• The for Loop
• A pre-test loop.
• Automatically executes an update expression at the end of each iteration.
• Used when the exact number of required iterations is known.

C++ Programming, Namiq Sultan 26


Random Number Generation
• rand(): returns a random number (int) between 0 and the largest int the
compute holds. Yields same sequence of numbers each time program is run.
• srand(x): initializes random number generator with unsigned int x

#include <iostream>
#include <cstdlib> // for srand() function
#include <ctime> // for time() function
using namespace std;
int main()
{ int a;
srand(time(0));
for(int i=0; i<10; i++)
cout<<rand()/1000<<" ";
return 0;
}

C++ Programming, Namiq Sultan 27


5.9 Nested Loops

• A loop that is inside another loop is called a nested loop.

C++ Programming, Namiq Sultan 28


Program 5-13
// This program averages test scores. It asks the user for the
// number of students and the number of test scores per student.

int main()
{
int numStudents, numTests, total, score;;
float average;
  cout << "This program averages test scores.\n";
cout << "For how many students do you have scores? ";
cin >> numStudents;
cout << "How many test scores does each student have? ";
cin >> numTests;

C++ Programming, Namiq Sultan 29


for (int count1 = 1; count1 <= numStudents; count1++)
{
total = 0; // Initialize accumulator
for (int count2 = 1; count2 <= numTests; count2++)
{
cout << "Enter score " << count2 << " for ";
cout << "student " << count1 << ": ";
cin >> score;
total += score; // accumulate running total
}
average = total / numTests;
cout << "The average score for student " << count1;
cout << " is " << average << ".\n\n";
}
return 0;
}

C++ Programming, Namiq Sultan 30


Program Output with Example Input
This program averages test scores.
For how many students do you have scores? 2 [Enter]
How many test scores does each student have? 3 [Enter]
Enter score 1 for student 1: 84 [Enter]
Enter score 2 for student 1: 79 [Enter]
Enter score 3 for student 1: 97 [Enter]
The average for student 1 is 86.
 
Enter score 1 for student 2: 92 [Enter]
Enter score 2 for student 2: 88 [Enter]
Enter score 3 for student 2: 94 [Enter]
The average for student 2 is 91.

C++ Programming, Namiq Sultan 31


5.10 Breaking Out of a Loop

• The break statement causes a loop to terminate early.

C++ Programming, Namiq Sultan 32


Program 5-14
// This program raises the user's number to the powers of 0 through 10.
#include <iostream>
#include <math>
using namespace std;
int main()
{
int value;
char choice;
  cout << "Enter a number: ";
cin >> value;
cout << "This program will raise " << value;
cout << " to the powers of 0 through 10.\n";

C++ Programming, Namiq Sultan 33


for (int count = 0; count < 10; count++)
{
cout << value << " raised to the power of ";
cout << count << " is " << pow(value, count);
cout << "\nEnter Q to quit or any other key ";
cout << "to continue. ";
cin >> choice;
if (choice == 'Q' || choice == 'q')
break;
}
return 0;
}

C++ Programming, Namiq Sultan 34


Program Output

Enter a number: 2 [Enter]


This program will raise 2 to the powers of 0 through 10.
2 raised to the power of 0 is 1
Enter Q to quit or any other key to
continue. C [Enter]
2 raised to the power of 1 is 2
Enter Q to quit or any other key to continue. C [Enter]
2 raised to the power of 2 is 4
Enter Q to quit or any other key to continue. Q [Enter]

C++ Programming, Namiq Sultan 35


Using break in a nested loop
• The break statement below breaks out of the inner loop but NOT
the outer loop
for(int row = 0; row < 5; row++)
{ //begin outer loop
for(star = 0; star < 20; star++)
{ //begin inner loop
…………// some statements
break;
…………// some more statements
} //end inner loop
} //end outer loop

C++ Programming, Namiq Sultan 36


Problems
1. Find the sum of the numbers 1, 2, 3, …, 40.
2. Find the sum of the odd numbers between 1 and 40.
3. Find the sum and average of odd numbers between 1 and 40.
4. Print the characters ‘A’, …, ‘Z’ along with their ASCII code equivalents.
The table should be displayed as the following:
A = 65
B = 66
.
.
Z = 90

5. Write a program that reads a set of numbers, and adds them together. The
program is terminated when the user inputs 0. Then the result of added
numbers is printed out.

C++ Programming, Namiq Sultan 37


Problems
6. Write programs that print the following shapes using loop statements.
* * 1 *
** ** 12 **
*** *** 123 * *
**** **** 1234 * *
***** ***** 12345 * *
****** ****** 123456 * *
******* ******* *******

7. What is the output of the following statements?


for (int i=1; i<=10; i++){
for (int j=1; j<=10-i; j++)
cout<<‘*’;
cout<< endl;
}
8. Find the result of the following summation, where n is an integer read from
the keyboard.
n
i2
i 1 i 1 38

You might also like