Professional Documents
Culture Documents
CS 201 Introduction To Computing: Fall 2021-2022
CS 201 Introduction To Computing: Fall 2021-2022
Introduction to Computing
Fall 2021-2022
Week-5
● Loops - repetition
o Counting loops
o Sentinel loops
o For Loops and While Loops
o Strings with loops
2
From Selection to Repetition
● The if statement and if/else statement allow a block of
statements to be executed selectively: based on a condition
● This piece of code does not ask another input if number < 0
● While statement repeatedly executes a block of statements
while the condition is true
cout << " Please enter a non-negative number" << endl;
cin >> inputnumber;
while (inputnumber < 0){
cout << inputnumber << " is negative! Try again"<<endl;
cin >> inputnumber;
}
Semantics of while loop
if (test){ while (test){
true true
test test
<initialization>
while (<test>)
{
<statement1>;
...
<statementN>;
<update>
}
Another simple example
i 1 2
int sum = 0; sum 0 1
int i = 1;
i<=10
while (i <= 10)
{
true false
sum = sum + i;
i = i + 1;
sum=sum+i;
} i=i+1;
cout << sum;
cout<<sum;
Walkthrough of the example
i 2 3
int sum = 0; sum 1 3
int i = 1;
i<=10
while (i <= 10)
{
true false
sum = sum + i;
i = i + 1;
sum=sum+i;
} i=i+1;
cout << sum;
cout<<sum;
Walkthrough of the example
i 3 4
int sum = 0; sum 3 6
int i = 1;
i<=10
while (i <= 10)
{
true false
sum = sum + i;
i = i + 1;
sum=sum+i;
} i=i+1;
cout << sum;
cout<<sum;
Walkthrough of the example
i 10 11
int sum = 0; sum 45 55
int i = 1;
i<=10
while (i <= 10)
{
true false
sum = sum + i;
i = i + 1;
sum=sum+i;
} i=i+1;
cout << sum;
cout<<sum;
while loop sum example
int sum = 0;
initialization
int i = 1;
while (i <= 10) test
{
sum = sum + i; body statements
i = i + 1; update
}
cout << sum;
Another easy example (not in book)
<initialization> for(<initialization>;<test>;<update>)
while(<test>) {
{ <statement1>;
<statement1>; ...
<statementN>;
...
}
<statementN>;
<update>
}
for loop example
void Vertical(string s)
// post: chars of s printed vertically // for loop alternative 1
int len; int k; int len; int k;
len = s.length(); len = s.length();
k = 0; for(k=0; k < len; k+= 1){
while (k < len){ cout << s.substr(k,1) << endl;
cout << s.substr(k,1) << endl; }
k += 1;
}
// for loop alternative 2
// for loop alternative 3 int len; int k;
int len; int k; for(len = s.length(), k=0; k < len; k+= 1){
len = s.length(); cout << s.substr(k,1) << endl;
k = 0; }
for(; k < len; k+= 1){
cout << s.substr(k,1) << endl;
}
Example: Print a string backwards
(revstring.cpp)
● Determine the index of the last character of the string,
and then access each character backwards
● How many times should the loop iterate ?
string s; int k;
cout << "enter string: ";
cin >> s;
cout << s << " reversed is ";
k = s.length() - 1; // index of last character in s
while (k >= 0){
cout << s.substr(k,1);
k -= 1;
}
cout << endl;
● What could we use instead of s.substr(k,1) ? s.at(k)
Reverse String as a function
● First step, what is the prototype?
string revstring(string s)
// pre: s = c0c1c2…cn-1
// post: return cn-1…c2c1c0
3. int i = 1;
while (i < 20) {
cout << "How many times do I print?";
}
Bad loops
● Never executes
● Never stops (infinite loops)
● Example: consider the following modified code from sum10nums
● What’s the problem in the loop below? What is missing?
sum = 0;
count = 1;
while (count <= 10){
cin >> num;
sum += num;
}
● How to fix?
● You can check whether num is even before starting the loop.
if (num % 2 == 0)
while (start != num){
start += 2;
cout << start << endl;
}
Other Common Problems
● Sometimes the proper loop test and body are hard to design
long factorial(long n)
// pre: 0 <= n
// post: returns n! (1 x 2 x … x n)
● Issues
● What happens if we initialize count to 1?
See bigfact.cpp
Determining if a number is prime
● Prime number is a natural number having only two divisors: 1 & itself
● Some Cryptographic algorithms depend on prime numbers
● Determining if a number is prime must be "easy"
● Actually factoring a number must be "hard"
● "hard" in the sense that it must be computationally infeasible to
factorize in a reasonable amount of time
● RSA Cryptosystem
● Rivest, Shamir, Adleman
● based on the factorization problem of large numbers
● has been utilized by several security products and services
● PGP (Pretty Good Privacy) – email security
● WWW security using SSL protocol
● Sophisticated mathematics used for fast prime-testing, we'll do basic
prime testing
● Since our algorithm is based on factorization, it will be really slow for
large numbers
Determining Primeness (continued)
● 1 is NOT prime, 2 is prime, 3 is prime, 17 is prime, … 137, 193?
● We don't need to check even numbers other than 2 (2 is special case)
● To check 193, divide it by 3, 5, 7, 9, 11, 13
● Note that 14x14 = 196, so 13 largest potential factor?
● We will use modulus operator to check divisibility
int power = 1;
int n, m;
cin >> n >> m;
for (int i = m; i >= 1; i--){
power = power * n;
}
Nested loops
● Sometimes one loop occurs in another
● Generating 2-dimensional tabular data
● multiplication table
● Sorting vectors (which will be studied much later)
● Display some geometric figures using character *
(or any other character)
● display rectangles, triangles
● See drawfigures.cpp for the complete function and its use in main
Nested loops - Example
● Write a function to display a perpendicular isosceles triangle of stars
(perpendicular side length is parameter)
● e.g. if side length is 5, the output should look like
*
**
***
****
*****
● See drawfigures.cpp for the complete function and its use in main
Same loop: downward-counting
for (i=1; i <= side; i++){ for (i=1; i <= side; i++){
for (j=1; j<=i; j++){ for (j=i; j>=1; j--){
cout << "*"; cout << "*";
} }
cout << endl; cout << endl;
} }
Drawfigures – Other Considerations
● What about having a function to display a line of stars
(number of stars is a parameter)
● useful for both rectangle and triangle
void PrintLine (int numstars){
// pre: numstars > 0
// post: displays numstars stars in one line
int i;
for (i=1; i<= numstars; i++)
cout << "*";
cout << endl; // end of line is put to the end of the line
}
int main(){
int i,k,numlines;
const int WIDTH = 4;
cin >> numlines;
{ <update> )
<statement1>; {
... <statement1>;
...
<statementN>;
<statementN>;
<update>
}
}
Example
● Rewrite the while loop of main of primes.cpp using for loop
k = low;
while (k <= high) for (k = low; k <= high; k += 1)
{ {
if (IsPrime(k)) if (IsPrime(k))
{ {
cout << k << endl; cout << k << endl;
numPrimes += 1; numPrimes += 1;
} }
k += 1; }
}
The do-while loop
● Similar to while loop, but test is after the execution of the loop body
● while loop may never execute, do-while loop executes at least once
<initialization>
do{
<statement1>;
...
<statementN>; Don't
<update> forget
} while (<condition>);
● Example: Prompt for a number between 0 and 100, loop until such a
number is entered (user should enter at least one number)
do{
cout << "enter number in range [0..100] ";
cin >> num;
} while (num < 0 || num > 100 );
while loop versus do-while loop
Priming
● Priming: reading an initial value before the loop
● do not get confused with prime numbers; this is something else
● Problem: enter numbers, add them up, stop when -1 entered
int sum = 0;
int num;
cin >> num; // prime the loop
while (num != -1){
sum += num;
cin >> num;
}
cout << "total = " << sum << end;
int sum = 0;
int num;
while (true){ // seemingly infinite loop
cin >> num;
if (num == -1)
break; // get out of loop
sum += num;
}
cout << "total = " << sum << end;
Fence Post Problem
● Problem that occurs when one or more operations of the loop
body are executed one less then the others
● Example: Display integers between 1 and 10 separated by comma
1,2,3,4,5,6,7,8,9,10
● no comma after 10; no comma before 1
uniqueDigits.cpp
Another Possible Exam Question
Write a C++ program that takes string inputs as words until
the user enters the word "end", case-insensitively, and
concatenates them to makeup a sentence (except for "end").
Your program should then display the most frequent character
appearing in the constructed sentence.