Loops in C++ - Reading Assignment

Part one:

1. What can we do with while statements?

We can repeat code as often as we like.

2. What value does the statement in brackets need to evaluate to in order for the loop to continue?

True

3. What is an infinite loop?

A loop that never ends.

4. What is an iteration?

A repetition of a loop is called an iteration.

Part two:

1. When is it a good idea to use a for statement (do a for loop) instead of the while loop we learned previously?

When one knows how many times to iterate.

2. How would you write a for-loop in code?

for (int x = 1; x <= 10; x++)
cout << x;

3. What is an off-by-one error?

When someone forgets an operator, eg: uses only one where two are need - < instead of <=.

1 Like

1. What can we do with the while statement?
if a statement is true we can excecute a code if not we don’t
2. What value needs the statement in the brackets evaluate to in order for the loop to continue?
all except 0
3. What is an infinite loop?
An expression that is always correct so keeps excecuting
4. What is an iteration?
the loop command is called an iteration

1. When is it a good idea to use a for statement (do a for loop) instead of the while loop we learned previously?
When I need to define, initialize, and change the value of a loop variable with every iteration.
2. How would you write a for-loop in code?
for(int x =0; x>=10; ++x){
//cout << x << end1;
}
3. What is an off-by-one error?
when your loop initiates one to many or few times mostly at right variables

1 Like

A while statement is declared using the while keyword. When a while statement is executed, the expression is evaluated. If the expression evaluates to true (non-zero), the statement executes. Once the statement has finished executing, control returns to the top of the while statement and the process is repeated.

boolean(TRUE)

If the expression always evaluates to true, the while loop will execute forever.

Each time a loop executes, it is called an iteration .

When we know exactly how many times we need to iterate, because it lets us easily define, initialize, and change the value of loop variables after each iteration.

for (int count{ 9 }; count >= 0; count -= 2)
std::cout << count << ’ ';

Off-by-one errors occur when the loop iterates one too many or one too few times. This generally happens because the wrong relational operator is used in the conditional-expression (eg. > instead of >=).

1 Like
  1. What we can do with a while statement is,… Create loops! Once the while statement finishes executing, control returns to the top of the statement, and it will repeat until a condition is met breaking out of the loop. Unless it is an infinite loop in which case the loop repeats indefinitely.

  2. The statement in the brackets must be true, in order for the loop to continue.

  3. An Infinite loop is a loop that continues to evaluate as true.

  4. Each time the loop executes it is called an iteration.

Part 2

  1. Using a for loop would be better in a circumstance where we are initializing the loop for a single time or set number of times. whereas the while loop is used an infinite number of times.

2.example : int main() {
for( int i = 0; i < 7; i++) {
cout << i << endl;
}
return 0; which will return 0,1,2,3,4,5,6

  1. off-by-one-error is when you expect a program to run 5 times but it runs 4 or 6 times. it happens due to an incorrect operator in place of the correct one.
1 Like

1. What can we do with the while statement?
A statement inside a while loop can executed over and over again as long as the condition after the while keyword is true.

2. What value needs the statement in the brackets evaluate to in order for the loop to continue?
This statement needs to be true (or to say it more precisely not zero).

3. What is an infinite loop?
An infinite loop will be executed over and over again, because the condition will never evaluate to false.

4. What is an iteration?
One execution of the statement(s) in the while loop is called an iteration. After each iteration the condition will be evaluated again to determine if another iteration will be performed.

1. When is it a good idea to use a for statement (do a for loop) instead of the while loop we learned previously?
If you know exactly how many times the code will be executed a for loop is preferable to a while loop.

2. How would you write a for-loop in code?
for (int index=0; index < iterations; index++) {
statement(s);
}

3. What is an off-by-one error?
An off-by-one error is when the number of desired iterations is off by one. So the code is executed one time less or one time more than desired.

1 Like

1. What can we do with the while statement?
run code in loop while a statement is true

2. What value needs the statement in the brackets evaluate to in order for the loop to continue?
1 //which is boolean true

3. What is an infinite loop?
a loop that has a statement that always is 1

4. What is an iteration?
each time a while loop runs it’s the next iteration

1. When is it a good idea to use a for statement (do a for loop) instead of the while loop we learned previously?
If you’re trying to write short code
Possibly to save on execution time

2. How would you write a for-loop in code?
for (initializing counter statement , boolean test , counter change )
{
code to be executed if true ;
}

3. What is an off-by-one error?
when a loop programmer doesn’t take into account the first or last value.
maybe by < instead of <=
maybe because of discounting the Zero

1 Like

True in c++ is any non zero value :slight_smile:

I would use for when I know how many iterations I want to make :slight_smile:

2 Likes

A while statement can be used to make a loop.

In order for the loop to continue, it must not have reached it’s goal. For example,
Int count { 0 };
while (count < 10) { — };
Loop will run 10 times, starting at 0 and stopping before 10.

An infinite loop is a loop whose statement is run over and over until it is stopped somehow.

An iteration refers to the execution of going one time around the loop.

It is a good idea to use a for statement instead of a while loop if you know the amount of iterations desired beforehand.

For (int count { 0 }; count < 10; ++count)
{
};

An off by one error refers to when you’ve set a specific number of iterations for a loop, but it’s off by one. The first iteration [0] was probably forgotten.

1 Like

Part one

  1. Repeatedly execute a block of code while the provided statement is true
  2. True
  3. if the expression always evaluates to true, the while loop will execute forever.
  4. One time execution of the block of code defined within the loop

Part two

  1. When I need to define, initialize, and change the value of a loop variable with every iteration.
  2. for(int x =0; x>=10; ++x){//cout << x << end1; }
  3. The error occures when the loop iterates one too many or one too few times.
1 Like

Create a loop that executes statements as long as the expression is true.

True.

The expression always evaluates to true, the while loop will execute forever.

Each time a loop executes, it is called an iteration.


For loop is ideal when we know exactly how many times we need to iterate.

for (init-statement; condition-expression; end-expression)
statement

Off-by-one errors occur when the loop iterates one too many or one too few times. This generally happens because the wrong relational operator is used in the conditional-expression (eg. > instead of >=).

1 Like

PART i

  1. Create a loop

  2. TRUE

  3. It is when the loop never breaks. When the Value is always True it will run forever.

  4. Each time a loop executes it is called a Interation

QUIZ TIME

  1. Inner is mentioned in the inner block so that it is recreated and initialized to 1.
  2. NOT A CHANCE IN ACHIEVING THIS. NEED WELL MORE HELP FOR THAT.
  3. HELP
  4. HELP

PART ii

  1. It is good for when you know how many times you want to iterate it. It gives us the ability to define, initialise, and change the value of loop variables after each iteration.

2.for (int count{ 0 }; count < 10; ++count) std::cout << count << ' ';

  1. These occur when the loop iterates one too many or too less times. Dangerous as it is tough to problem solve as the program will run but will execute the wrong result in the end.
1 Like

Lesson questions:

  1. repeatedly check to see if certain conditions are met, then preform a function.
  2. For the statement in the brackets to execute, the information inside the parenthesis must be true. If it is not true, then the code will not execute.
  3. An infinite loop is a loop where the results are never false, so it continues to iterate.
  4. An iteration is each time that the loop results return to the top of the loop.

While loop questions:
Question 1:
In the above program, why is variable inner declared inside the while block instead of immediately following the declaration of outer?
The location determines when the function is called. If you move it to another place, it will not run in the way that it should.

Question 2:
Write a program that prints out the letters a through z along with their ASCII codes. Hint: to print characters as integers, you have to use a static_cast.

#include
using namespace std;
int main()
{
char mychar{ ‘a’ };
while (mychar <= ‘z’)
{
std::cout << mychar << ’ ’ << static_cast(mychar);
if(mychar % 4==0)
{
std::cout <<’\n’;
}
++ mychar;
}
return 0;
}

Question 3:
/

#include

int main(int argc, const char * argv[])
{
int outer{5};
while (outer>=1)
{
int inner{outer};
while (inner>= 1)
{
std::cout <<inner-- << ’ ';

    }
    std::cout<<'\n';
--outer;
}

}

question 4
X X X X 1
X X X 2 1
X X 3 2 1
X 4 3 2 1
5 4 3 2 1
figure out how to make this pattern:
(the solution in the book is missing the “x”)

#include

int main(int argc, const char * argv[])
{
int outer{1};
while (outer<=5)
{
int inner {5};

    while (inner>=1)
    {
        if (inner<=outer)
            std::cout <<inner<<' ';
        else
            std::cout<<"X ";
        --inner;
    }
    std::cout<<'\n';
    ++outer;
}

}

For loop exercise: print out the even numbers between 1 and 20:
#include

int main(int argc, const char * argv[])
{

for (int grain =0; grain <= 20; grain++)
{
    if (grain % 2 == 0)
        std::cout<<grain <<' ';
}

}
Add the components of an array 1-5:
{
int myArray [5] {1,2,3,4,5};
int sum =0;
for (int i=0; i<5; i++)
{
sum+=myArray[i];
}
std::cout<<"sum = "<<sum;
}

What’s wrong with this:

1
2
3
// Print all numbers from 9 to 0
for (unsigned int count{ 9 }; count >= 0; --count)
std::cout << count << ’ ';
The loop will continue to run. Because it is unsigned, it will never turn negative.

1 Like

ASCII characters are represented as numbers, for example A is 65, so its just a matter of looping through the characters as if it were numbers and cast them to an interger. :slight_smile:

Here you need to write a nested loop, you have to make the nested loop to do one less iteration for each iteration of the main loop :slight_smile:

Here you will have to do the opposite and replace the iterations with the number of spaces, for X you can either use two nested loops or use some imagination how to make it more efficient :wink:

If you’re not sure you can always peek at the solution to the quiz on the site. But I encourage you to try to make your own solution.

2 Likes

A1) We can create loops with the while statement.
A2) In order for the loop to continue the expression value must be entered into the statement.
A3) An infinite loop is one that will execute forever as long as the expression value reads “true”.
An infinite loop will never terminate unless it has a return, break, exit, goto statement, an exception or the user kills the program.
A4) An iteration is every instance a loop is executed. Variables within a loop body is known as a block. The contents of the loop body (block) is created and destroyed at every instance of an iteration.

1. When is it a good idea to use a for statement (do a for loop) instead of the while loop we learned previously?
2. How would you write a for-loop in code?
3. What is an off-by-one error?

A1) When we know how many iterations is required it would a good idea to use a for loop, because it is easier to define, initialise and change the variable value after each iteration.

A2)
for (int count{0}; count <10; ++count) // this is the init-statement declared with a type and a variable name “count” and initialised with a value of 0.

count < 10; // this is the condition-expression, if it evaluates to true the statement is executed, if its a false its terminated.

++count) // this is the end-expression statement which is evaluated to increase or decrease the variables in the init-statement. Once evaluated the loop returns to the condition-expression state for reevaluation and iteration.

std::cout << count << ’ '; // prints result to console

A4) An off-by-one-error is when a loop iterates one too many or few times due to user failing to input an operator in the condition-expression statement.

1 Like

Appreciate the help Alko :+1:

  1. Thanks for the reply. I had to look at the solution in the end. Nothing in that Article telling me about mychar so how was i supposed to work that out? its like you’re giving a task and not being shown examples of solving it. I feel ive failed this because ive not been able to have a crack at it.

Ill write this in reviews but here is my thought so far. Ivans courses are great but there is a level of Basic Knowledge needing taught here in order to crack these Exercises…

Ill give the other one a bash tomorrow.

Rob.

1 Like

mychar is a variable name, you could use any name you want :slight_smile:

I know its difficult to learn programing at first, you have to learn an entire new way of thinking, the way of the programmer :stuck_out_tongue: This is the hardest part and the only way to conquer it is by practicing. Once you get the hang of it, it becomes second nature :slight_smile:

2 Likes

Thanks brother I’ll keep at it. I really do enjoy it and I am sitting down with it each day.

I have a ETH smart contract question. Off topic from the C++. But I’m after someone to take a look at a smart contract from a recent scammer to try and figure out how they do this and what goes on. I’m intrigued. Is there any where I should point this topic to help with students in the academy?

Rob

For Question #4, wouldn’t it be better to not use an if statement if possible? My solution (which worked) utilized only while loops and to me seemed easier/cleaner/shorter than the solution on learncpp.com:

int main()
{

    int outer = 1;

    while(outer <= 5){
        int inner = 5;

        while(inner > outer){
            cout << "  ";
            --inner;
        }
        while(inner <= outer && inner >= 1){
            cout << inner << " ";
            --inner;
        }

        ++outer;
        cout << "\n";
    }

    return 0;
}
1 Like

Programming is kind of like art, meaning no two developers will ever write the same piece of code.
Using two nested while loops instead of if statement is fine in this example :slight_smile:

1 Like