#include <iostream>
using namespace std;
int main (void) {
cout << " 1\t2\t3\t4\t5\t6\t7\t8\t9" << endl << "" << endl;
for (int c = 1; c < 10; c++) {
cout << c << "| ";
for (int i = 1; i < 10; i++) {
cout << i * c << '\t';
}
cout << endl;
}
return 0;
}
Hey so this code produces a times table...I found it on Google Code's C++ class online...I'm confused about why "i" in the second for loop resets to 1 every time you go through that loop...or is it being declared again in the first parameter?
Thanks in advance!
It "reverts" to 1 because you explicitly set it to 1 as the start condition of the loop...
The "i" name does not exist outside this loop, so each time this loop is run (for each iteration of 'c'), then "i" is a new variable, set to a start of 1.
As TZHX has written. FOR statements usually have three clauses that are in the parantheses (technically they always have three but you don't have to specify them), and a statement that is repeated (often a statement block).
Of those three clauses, the first is an initializer, the second controls the looping, and the third is the increment. So as TZHX says, i is reset to 1 at the beginning due to the initializer clause. This will keep repeating while i<10 (the second clause), and i is incremented by 1 with each iteration (the third clause).
Related
so i get how sentinel loops work, they use the expression at the beginning of the the loop declaration to determine where the loop stops. However i don't understand how to connect variables in the scope of the loop and outside the scope. For example
int i;
int sum = 0;
cout << "Enter a number" << endl;
cin>> i;
while (i > 0)
{
sum = sum + i;
cout << "Enter a number" << endl;
cin>> i;
}
cout << "The sum of the numbers entered is" << endl;
cout << sum;
return 0;
So the sum in the loop is correct since its within scope but the i or number entered to define i out of the scope in the initial i . How do you go about this, can you connect the variables inside and outside the loop? Or can you use uninitialized memory to make a sentinel loop? Do you have to add a separate variable outside the loop and connect the sum of i outside and inside the loop? So just trying to understand how you'd connect the variables inside and outside the scope. If sentinels need to have the variable defined prior to the loop.
Thank you for any light you can shed on this.
Variables are defined in a particular scope and become visible to all scopes within the outer scope unless overwritten (which most programmers tell you is a very, very bad idea). For instance:
#include
using std::cout;
using std::endl;
int main(int, char **) {
int i = 5;
int k = 10;
if (true) {
int j = 15;
int i = 20;
cout << "i inside if: " << i << ". J: " << j << endl;
}
cout << "i outside if: " << i << ". K: " << k << endl;
}
Running it produces:
i inside if: 20. J: 15
i outside if: 5. K: 10
In this case, the scope of method main() contains two variables, i and k. Those variables are also available inside the if-statement. The if also defines two variables, j and i. They are only available inside the if-statement.
The i inside the if-statement hides the larger i (which is dangerous / confusing), but I wanted to demonstrate it. As you can see, i outside the if retains it's original value -- it wasn't modified when we declared the inner copy.
In your code, i and sum are defined outside the if-statement, so they're available inside it, and changes you make to them persist. That is, because you haven't defined new variables, everything just works.
So I have a stack example I created following a tutorial using the stack library
stack<string> custs;
custs.push("george");
custs.push("louie");
custs.push("florence");
// cout << "size" << custs.size() << endl;
if (!custs.empty()) {
for (int i = 0; i <= custs.size(); i++) {
cout << custs.top() << endl;
custs.pop();
}
}
I ran this and got the output:
florence
louie
My question is why isn't it outputting George as well? The program outputs the top data then pops it. This means it should output Gorge then pop it after. Why doesn't this happen? initially the code was i < cust.size so I thought because i is not less than 1 it would not ouput. So I switched it to <= and it still doesn't output George. How come?
It is because you are both increasing i and reducing the size of the stack in the loop.
You can rewrite your loop like this:
while (!custs.empty()) {
cout << custs.top() << endl;
custs.pop()
}
Here is a step by step explanation of what is happening so you can understand it better:
First, i starts as 0, and custs.size() returns 3. Since 0 <= 3 is true, the body of the loop executes, printing "florence" and removing it from the stack.
On the second iteration, i equals 1, and custs.size() returns 2, because you had 3 items but you removed one. Since 1 <= 2 is true, the body of the loop executes again, printing "louie" and removing it from the stack.
Then, i equals 2, and custs.size() returns 1, because you already removed 2 elements. Since 2 <= 1 is false, the body of the loop doesn't execute, and the loop ends.
As you can see, the problem is that your loop's condition changes on each iteration. There are a couple of ways to fix this:
int s = custs.size();
for (int i = 0; i < s; i++) {
cout << custs.top() << endl;
custs.pop();
}
By doing that, you store the original size of the stack, so you can iterate without problems.
Another solution would be to check if the stack is empty on each iteration with a while loop:
while (!custs.empty()) {
cout << custs.top() << endl;
custs.pop();
}
By doing that, you check if there are any elements left to print each time.
Hope this helps!
When you use for loop like this
for (int i = 0; i <= custs.size(); i++) {
cout << custs.top() << endl;
custs.pop();
}
it loops directly till the size of stack which decreases in each iteration.
which in my opinion is the main reason your code is not working. I rewrite this as
int z = custs.size() ;
for(int i=0;i<=z;i++)
{
cout<<custs.top()<<endl;
custs.pop();
}
and it worked perfectly fine. In my opinion, the best approach is to use while loop like this
while(!custs.empty())
{
cout<<custs.top()<<endl;
custs.pop();
}
I am a c++ beginner and I hope you could help me with some of the fun I am having, you all know what I actually mean.
Here is a snippet of c++ code that I will follow with a brief explanation my problem:
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main() {
// this first for loop doesn't affect the execution of the first cout statement.
for (int i = 51; i >= 0; i--) {
srand(time(NULL));
int j = rand();
cout << j << endl;
};
cout << "first cout outside the first for loop" << endl; // executes fine
// this second for loop affects the execution of the following cout statement.
for (int i = 51; i >= 0; i--) {
srand(time(NULL));
int j = rand() % i; //by just adding % i, the next cout statement doesn't execute!
cout << j << endl;
};
cout << "second cout outside the second for loop" << endl; // doesn't execute
}
All right, so, I hope the issue is obvious. To put it in words, why adding the modulus i to the rand() in the second for loop prevents the second cout statement from execution? It took me a whole lot of time to pinpoint what seems to be a big problem in my entire class implementation to this single line. Any feedback/advise/explanation is greatly appreciated.
Cheers.
Programs that execute undefined behavior can have any apparent behavior, including code "in the past" not executing.
You do %0 at the end of your loop. This makes earlier print statements not output. That is acceptable behavior as far as C++ is concerned.
Don't do undefined behavior.
This question already has answers here:
'do...while' vs. 'while'
(31 answers)
Closed 8 years ago.
I would like someone to explain the difference between a while and a do while in C++
I just started learning C++ and with this code I seem to get the same output:
int number =0;
while (number<10)
{
cout << number << endl;
number++
}
and this code:
int number=0;
do
{
cout << number << endl;
number++
} while (number<10);
The output is both the same in these both calculations. So there seem to be no difference.
I tried to look for other examples but they looked way to difficult to understand since it contained mathemetical stuff and other things which I haven't quite learned yet. Also my book gives a sort of psychedelic answer to my question.
Is there an easier example to show the difference between these 2 loops?
I was quite curious
The while loop first evaluates number < 10 and then executes the body, until number < 10 is false.
The do-while loop, executes the body, and then evaluates number < 10, until number < 10 is false.
For example, this prints nothing:
int i = 11;
while( i < 10 )
{
std::cout << i << std::endl;
i++;
}
But this prints 11:
int j = 11;
do
{
std::cout << j << std::endl;
j++;
}
while( j < 10 );
The while loop is an entry control loop, i.e. it first checks the condition in the while(condition){ ...body... } and then executes the body of the loop and keep looping and repeating the procedure until the condition is false.
The do while loop is an exit control loop, i.e. it checks the condition in the do{...body...}while(condition) after the body of the loop has been executed (the body in the do while loop will always be executed at least once) and then loops through the body again until the condition is found to be false.
Hope this helps :)
For Example:
In case of while loop nothing gets printed in this situation as 1 is not less than 1, condition fails and loop exits
int n=1;
while(n<1)
cout << "This does not get printed" << endl;
Whereas in case of do while the statement gets printed as it doesn't know anything about the condition right now until it executes the body atleast once and then it stop because condition fails.
int n=1;
do
cout << "This one gets printed" << endl;
while(n<1);
If you consider using a different starting value you can more clearly see the difference:
int number = 10;
while (number<10)
{
cout << number << endl;
number++
}
// no output
In the first example the condition immeditately fails, so the loop won't execute. However, because the condition isn't tested until after the loop code in the 2nd example, you'll get a single iteration.
int number = 10;
do
{
cout << number << endl;
number++
}
while (number<10);
// output: 10
The while loop will only execute of the conditions are met. Whereas the do while loop will execute the first time without verifying the conditions, not until after initial execution.
So I create and initialize a vector (of size nmask+3) to 0, and I assign an initial value to one of the elements. I then make a for loop that goes through the first nmask elements of the vector and assigns to each element an average of 26 other elements in the vector (defined by the 4D int array voxt, which contains vector addresses).
My problem is that when I check the values of nonzero elements in my vector (phi) within the nested loop (the first cout), the values are fine and what I expect. However, when the loop finishes going through all nmask elements (for (int i= 0; i<nmask; i++) exits), I check the nonzero elements of phi again, and they are all lost (reset to 0) except for the last non-zero element (and element tvox which is manually set to 1).
I feel that since phi is initialized outside of all the loops, there should be no resetting of values going on, and that any updated elements within the nested loop should remain updated upon exit of the loop. Any ideas as to what is going on / how to fix this? Code is below; I tried to comment in a sense of the outputs I'm getting. Thanks in advance.
vector<double> phi(nmask+3, 0); //vector with nmask+3 elements all set to 0 (nmask = 13622)
phi[tvox]= 1; //tvox is predefined address (7666)
for (int n= 0; n<1; n++)
{
vector<double> tempPhi(phi); //copy phi to tempPhi
for (int i= 0; i<nmask; i++)
{
for (int a= -1; a<=1; a++)
{
for (int b= -1; b<=1; b++)
{
for (int c= -1; c<=1; c++)
{
if (!(a==0 && b==0 && c==0))
{
//oneD26 is just (double) 1/26
phi[i]= tempPhi[i]+oneD26*tempPhi[voxt[i][1+a][1+b][1+c]];
if (phi[i]!=0)
{
//this gives expected results: 27 nonzero elements (including tvox)
cout << n << " " << i << " " << a << b << c << " " << phi[i] << endl;
}
}
}
}
}
}
phi[svox]= 0; //svox = 7681
phi[tvox]= 1;
for (int q= 0; q<nmask; q++)
{
//this gives only 2 nonzero values: phi[tvox] and phi[9642], which was the last nonzero value from 1st cout
if (phi[q]!=0)
cout << q << " " << phi[q] << endl;
}
}
Difficult to tell just what is going on, but the easiest explanation is that after phi[i] gets set to non-zero and displayed to cout, it gets set to zero again in one of the later iterations through the inner loops.
If you do some tracing and check phi[i] just before updating you'll see that you often overwrite a non-zero element with zero.
Note: I have no idea what your code does, this is pure Sherlock Holmes reasoning.. if after the loops you find only 2 non-zero elements then the only logical consequence is that after updating something to non-zero later in the loop you update it to zero.
phi[i]= tempPhi[i]+oneD26*tempPhi[voxt[i][1+a][1+b][1+c]];
The nested for-loops using a, b, and c run for a combined 9 iterations with the same value of i. Since you overwrite phi[i] to a new value every time, you only retain the value from the last iteration where a, and c are all 1. If that last iteration happens to produce zero values, then phi[i] will have lots of zeroes. Perhaps you meant to do something like phi[i] += ... instead of phi[i] = ...?
I do suggest to replace the meat of the loop with something like
const boost::irange domain(-1,2);
for (int i: boost::irange(0, nmask)) for (int a: domain) for (int b: domain) for (int c: domain)
{
if (a==0 && b==0 && c==0)
continue;
//oneD26 is just (double) 1/26
phi[i]= tempPhi[i]+oneD26*tempPhi[voxt[i][1+a][1+b][1+c]];
if (phi[i]!=0)
{
//this gives expected results: 27 nonzero elements (including tvox)
cout << n << " " << i << " " << a << b << c << " " << phi[i] << endl;
}
}
Of course, for brevity I assume both boost/range.hpp and c++0x compiler. However, with trivial macro's you can achieve the same. That is without writing/using a proper combinations algorithm (why is that not in the standard, anyway).