Loops in C++ - Reading Assignment

Right, this question below was not clear to me from the solution they provided,

Write a function named sumTo() that takes an integer parameter named value, and returns the sum of all the numbers from 1 to value.

For example, sumTo(5) should return 15, which is 1 + 2 + 3 + 4 + 5.

Hint: Use a non-loop variable to accumulate the sum as you iterate from 1 to the input value, much like the pow() example above uses the total variable to accumulate the return value each iteration.

Part 1

  1. While loop is like a for loop but like in javascript we usually use while loop when we don’t actually knew when will the loop ends because while loop will continue unless the statement would result into false.

  2. The statement should return true for the loop to continue.

  3. Infinite loop is a loop that never break, to avoid this create something in the condition that would return false in the end to avoid the infinite loop.

  4. The execution of a loop.

Part 2

  1. We use for loop when we know how many times to iterate a loop while while loop is we don’t know how many time we will need to iterate.

  2. for (int i=0; i<10; ++i);{
    cout << i << endl;
    }

  3. When the loop iterates one too many or one too few times to produce the desired result.

1 Like

You can use the number as the iterator and use it in the loop to sum the values and return the result.
I’m not sure what was the provided solution but you can make your own based on your understanding as long as it does what is required. :slight_smile:

  1. By using a while loop we are able to write code that makes it easier to compile large sets of numbers.

  2. A condition that evaluates to true is need in order for a loop to continue.

  3. An infinite loop is an expression that always evaluates to true, causing the loop to never end.

  4. An iteration is a way to exit an infinite loop.

  5. It is a good idea to use a for loop when there is an obvious loop variable.

  6. for(init-statement; condition; end expression)
    statement.
    for(int count{1}; count<=10;++count)
    std::cout<<count<<’ ';
    return 0;

  7. An off-by-one error is an error that occurs when a loop returns one too many or one too few times to produce a result.

1 Like

What can we do with the while statement?
While is a loop that keeps on until the expression is false.

What value needs the statement in the brackets evaluate to in order for the loop to continue?
The statement must be true.

What is an infinite loop?
It’s a never ending loop. Giving the While loop as example, if he is defined as true in boolean we will iterate forever.

What is an iteration?
Each complete loop is an iteration.

When is it a good idea to use a for statement (do a for loop) instead of the while loop we learned previously?
Mainly when we want to specify how many loops will be made.

How would you write a for-loop in code?
for (int i=0; i<5; i++){
//code in loop
}

What is an off-by-one error?
It’s when a for loop runs too many / few times than what was expected to do. It may happen when we have an error in our conditional expression, for example a mistyped operator.

1 Like
// First Answers

1- while allows a piece of code to execute repeatedly until given condition within the while statement is met.

while (condition) {
    statement;
}

2- While statement is repeated until the condition is false, so it repeats while the value is true.

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

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

// Second Answers

1- When there is an exact number of iteration, we can use for loop. If the iteration number is undefined, we can use while .

2-

`for (init-statement; condition; end-expression)` 
` statement`
for (int count{ 1 }; count <= 10; ++count)
        std::cout << count << ' ';
 1 2 3 4 5 6 7 8 9 10

3- Off-by-one errors occur when the loop iterates one too many or one too few times to produce the desired result. For example ; using the wrong relational operator, using pre-increment or pre-decrement instead of post-increment or post-decrement, or vice-versa.

1 Like

Part 1

  1. What can we do with the while statement?
    Loop until a specified condition is true

  2. What value needs the statement in the brackets evaluate to in order for the loop to continue?
    true .

  3. What is an infinite loop?
    An infinite loop occurs when a condition always evaluates to true

  4. What is an iteration?
    The statements that cause a set of statements to be executed repeatedly either for a specific number of times or until some condition is satisfied.

Part 2

  1. When is it a good idea to use a for statement (do a for loop) instead of the while loop we learned previously?
    Once we know how many times we have iterate the loop.

  2. How would you write a for-loop in code?
    int main() {
    for (int i = 0; i < 5; i++) {
    cout << i << “\n”;
    }

  3. What is an off-by-one error? Is when the loop iterates one too many or one too few times to produce the desired result.

1 Like

1/1. We can repeat things easily.
1/2. True.
1/3. A loop that has a condition which always evaluates to true, therefore will repeat itself infinite times.
1/4. One execution of a loop.

2/1. When we have a counter value, that indicates when to stop the loop.
2/2. for(init-statement; condition; end-expression) (i.e. for(int i = 0; i <= 10; ++i))
2/3. When the loop finishes one step sooner or one step later than intended.

1 Like

Part 1

  1. What can we do with the while statement?

With the while statement it is possible to run a specific piece of code repeatedly while a specific condition is true.

  1. What value needs the statement in the brackets evaluate to in order for the loop to continue?

The while loop will continue to run as long as the boolean value of the condition evaluates to “true”.

  1. What is an infinite loop?

As the name implies, an infinite loop will run forever. This happens, when the condition’s boolean value always evaluates to true and there is no other exit statement inside the loop’s body, e.g. a break statement.

  1. What is an iteration?

An iteration is the process of the loop body being executed.

Part 2

  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 the loop uses one or multiple specific loop variable(s) it is a good idea to use a for loop instead of a while loop because using a for loop is more convenient in defining the variables and it is easier to read what changes take place after each iteration.

  1. How would you write a for-loop in code?
for(int i{0}; i < 10; i++){
statement(s);
}
  1. What is an off-by-one error?

This error is usually the result when a loop iterates one time too few or too many and thus creates a result that is off by one iteration.

1 Like
  1. Create a simple loop that will run until the condition evaluates to false.

  2. True

  3. A loop that never ends, it executes forever.

  4. Every time a loop executes it is an iteration.

  5. For loops are more useful when the number of iterations is known and they provide a cleaner, more concise way of writing a loop.

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

  7. This happens when a loop is iterated one too many or one too few times due to an “equal to” mistake in the condition.

1 Like

1. What can we do with the while statement?

Iterate through the while loop as long as the While condition is true

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

While loop conditions need to evaluate to true

3. What is an infinite loop?

An infinite loop is a loop with no exit condition (runs forever as the While condition is always true)

4. What is an iteration?

An iteration is a single execution of the loop

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

It is better (cleaner) to use a for loop when you have a loop variable and know how many times you need to execute the loop

2. How would you write a for-loop in code?
for (initialize variable; condition to check for; action to take at the end - generally increment/decrement counter). i.e. for (int count = 0; count <=10; ++count)

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

A one-off error is a programming mistake where you have one too many (or too few) iterations of a loop

1 Like

1 & 2) loop through the statements contained in the while loop, as long as the initial condition of the loop is met (the entry condition is “true”).

  1. a loop whose initial condition always is “true” and consecuently never stops executing.

  2. an iteration is each time a loop executes. We also say “iterate through a loop”.


part 2:

  1. We should use a for loop when we know exactly how many times we want to execute it. (e.g. do something x times)

for (int count=0; count <100 ; ++count)
    {
    cout << count << endl;
    }

This is a for loop that prints from 1 to 100

  1. An off-by-one error is a common error in for-loops where the programmer uses the wrong operator for the for-loop rules. For example, if we want to print a count from 1 to 100, the correct versin would be:
    for (int count=0; count <100 ; ++count)
    An off-by-one error would count one time more or one time less than intended, for example:
    for (int count=1; count <100 ; ++count) -> here we count only from 1 to 99.
1 Like

FORUM QUESTIONS
Part 1

  1. What can we do with the while statement?
    A while statement is a loop which takes some argument (condition) and some block of code (body). The compiler will look at the condition and deem whether it is true, or false. When the condition is true, the code in the body will execute. After the body has been executed, the compiler will go back to the condition and assess whether it is still true. If it is, the body code is executed again.
    This process repeats as a loop until the point where the condition is false, where the compiler will skip the body of the loop and continue executing the rest of the program.
    We can run a while statement until the condition is false, or have the loop run indefinitely.

  2. What value needs the statement in the brackets evaluate to in order for the loop to continue?
    The statement in the brackets (the condition) needs to be true in order for the loop to continue.
    If the condition is false, the loop will exit.

  3. What is an infinite loop?
    An infinite loop when the condition never resolves to false. This means the loop continues to run until the program is exited. An example of where this is useful is a messaging platform where the program continuously checks the server for new data (messages). We don’t want these requests to cut out unexpectedly, so we run an infinite loop for this example.

  4. What is an iteration?
    An iteration is one instance of the loop body being executed. So an iteration will occur when the compiler deems the condition to be true, and will proceed to run the code.
    The compiler will then return to the condition to assess the Boolean value again. If it is true, the program will enter its second iteration.
    The program continues to cycle through iterations until the loop condition is false.

Part 2

  1. When is it a good idea to use a for statement (do a for loop) instead of the while loop we learned previously?
    A while loop is sufficient for simple loops, however a for loop is far easier to manage obvious loops.
    A for loop can concisely define, initialize, test, and change the value of loop variables in the opening condition, whereas counter variables are changed within the loop body in while loops.
    In for loops, all of this is defined and maintained in the condition statement.

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

for (int counter = 0; counter <= 10; ++counter) 
  cout << "I have " << counter << " points." <<endl;
  1. What is an off-by-one error?
    An off-by-one error is a common mistake some coders make when referring to array indexes. This occurs when they forget to take into account that an array will start with a 0 index.
    These errors can be propagated to programs through loops when the set the condition to execute until, for example counter = 11, instead of 10, as it loops through an array.

ARTICLE QUESTIONS
Part 1

  1. In the above program, why is variable inner declared inside the while block instead of immediately following the declaration of outer ?
    For the program to act in a desirable manner, the inner code moves before the outer code. So the outer counter is set to 1 and then the inner counter catches up, and when it surpasses outer, it moves on and executes the code from the outer loop, creating a new line to start again.
    If the inner loop was declared outside and after the outer loop, you would just get 5 blank lines and then a count of 1 to 5 on one line.

  2. Invert the nested loops example so it prints the following:

#include <iostream>
using namespace std;
 
int main()
{
    int outer{5};
    while (outer >= 1)
    {
        int inner = outer;
        while (inner >= 1)
        {
            cout << inner << ' ';
            --inner;
        }
        cout << endl;
        --outer;
    }
    return 0;
}
  1. Now make the numbers print like this:
#include <iostream>
using namespace std;

int main()
{
    int outer{1};
    while (outer <= 5)
    {
        int inner = 5;
        while (inner > outer)
        {
            cout << "  ";
            --inner;
        }
        while (inner >= 1) {
            cout << inner << " ";
            --inner;
        }
        cout << endl;
        ++outer;
        }
    return 0;
}

Part 2

  1. Write a for loop that prints every even number from 0 to 20.
#include <iostream>
using namespace std;

int main()
{
    for (int counter = 0; counter <= 20; counter += 2)
        cout<< counter << " ";
    return 0;
}
  1. Write a function named sumTo() that takes an integer parameter named value, and returns the sum of all the numbers from 1 to value.
    For example, sumTo(5) should return 15, which is 1 + 2 + 3 + 4 + 5.

I couldn’t get this to compile properly so any advice would be nice as to where I’m going wrong. Am getting an error when initializing the function.
Error is: A funtion definition is not allowed here before the ‘(’ token.
Thanks!

#include <iostream>
using namespace std;

int main()
{
    int sumTo(int value) {
        int total = 0;
        for (int counter = 1; counter <= value; ++counter)
            total += counter;
            return total;
    }
    cout<< sumTo(5);
    return 0;
}
  1. What’s wrong with the following for loop?
    As the count variable has been called as unsigned, it will never have a negative value.
    As the condition is count >= 0, a negative value is required for the function to be false, so this loop will run indefinitely.
1 Like

R1

  1. What can we do with the while statement?
    Continuously execute a block of code while the provided condition evaluates true.

  2. What value needs the statement in the brackets evaluate to in order for the loop to continue?
    True

  3. What is an infinite loop?
    If the expression always evaluates to true, the while loop will execute forever.

  4. What is an iteration?
    Each time a loop executes.

R2

  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 we have an obvious loop variable

  2. How would you write a for-loop in code?
    for (init-statement; condition; end-expression)
    statement

  3. What is an off-by-one error?
    Occurs when the loop iterates one too many or one too few times to produce the desired result.

1 Like
  1. What can we do with the while statement?

While let’s a user loop a statement under a certain condition.

  1. What value needs the statement in the brackets evaluate to in order for the loop to continue?

As long as the value of the statement is true, the while loop will continue.

  1. What is an infinite loop?

When an expression always evaluates to true, the loop continues infinitely, hence the infinite loop.

  1. What is an iteration?

An iteration is the numbered time a loop occurs.

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

For statements are convenient for when the user knows exactly how many iterations the loop needs.

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

For statements are written as follows:
for (int number = 0; number < 20; counter++)

cout << counter << endl;

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

Off-by-one errors occur when a loop iterates one too many or one too few times to produce the desired result.

1 Like
  1. make a loop

  2. while (count <= 10)

  3. a loop that has a condition that cannot be false

  4. an iteration lets you run an action per something that happens

///

  1. we use a while loop when we dont knw how many times we are going to keep running the loop

2.for (int count{ 1 }; count <= 10; ++count)

3.Off-by-one errors occur when the loop iterates one too many or one too few times to produce the desired result

1 Like

Reading 1

  1. We can make statements execute continually as long as its condition remain true.

  2. Not sure if I understood the question, but I believe as long as the value of the variable used in the loop is within the range of values determined by the while statement, it continues to execute.

  3. A loop that keeps repeating forever.

  4. One full execution of a loop.

1 Like

Reading 2

  1. Whenever you have an obvious loop variable (counter).

  2. for (initial statement; condition; end statement);

  3. It’s when the loop iterates one too many or one too few times.

1 Like
  1. The while statement can iterate a piece of code (“statement”) multiple times as long as a “condition” is true.
  2. True.
  3. A loop with a condition that will never become false and therefore will iterate forever.
  4. The “iteration” is a single execution of the loop’s code.

  1. Both “while” and “for” loops can be used in order to produce the same results, however “for” loops are preferable when there is an obvious loop variable as it is easier and more concise to initialize, test and manipulate.
  2. for (var_initialization; var_condition; expression_after_iteration) {statement}
  3. Off-by-one is a common mistake for new programmers (that sometimes also experienced ones do!) that occurs when there is one more (or one less) iteration than desired.
1 Like
  1. looping something until the statement in the brackets is false
  2. true
  3. a loop that never stops, because the testing statement always returns true
  4. one execution of the code block that loops
  5. when you know exactly how many iterations you need
  6. for(int counter = 0; counter<10; counter++){
    //do Stuff
    }
  7. a coding error that leads in a loop that does 1 iteration too much or 1 too few.
1 Like