Cod Pod Tracks
Cod Pod Tracks

Reputation: 17

How do I print a variable that is declared inside a for loop?

I am very new to C++ and am stuck in this little project I've been working on. If you look at the code, towards the very end I try to display the 'high' variable, but it only returns the value originally declared instead of displaying the value it was assigned in my loop statement. I know what's not working, I just don't know how exactly too fix it. So how do you print a variable that was declared in a loop outside of said loop?

#include <iostream>
#include <vector>
using namespace std;

int main() {
cout << "\t****Pancakes****" << endl << endl;

vector<int> pan_ate;

int people;
int high = 0;

cout << "How many people ate pancakes: ";
cin >> people;

for(int i = 1; i <= people; i++) {
int eat;
cout << "How many pancakes did person " << i << " eat? ";
cin >> eat;
pan_ate.push_back(eat);

}

for(int u = 0; u <= pan_ate.size(); u++) {

        if(pan_ate[u] > pan_ate[u + 1]) {
            high = pan_ate[u];
        }

 }
 cout << "The highest amount of pancakes ate was: " << high;
}

Upvotes: 0

Views: 814

Answers (1)

Jasper Niebuhr
Jasper Niebuhr

Reputation: 57

First of all there is no problem with assigning a value to a variable declared outside a loop/scope and accessing it later to output it. If high was set by the loop, you would output the result correctly.

There is a problem with the second loop itself however... The pan_ate.size() function returns the amount of elements in the vector. If there are e.g. 5 elements in it, they are at the indices 0, 1, 2, 3 and 4. Your loop however is also running for u = 5 (see 5 <= 5) and therefore accessing an element which isn't actually in that vector. Even further out of the vectors range is pan_ate[u + 1].

Since you are accessing memory from potentially an entirely different thing (likely just uninitialized memory) there is lots of potential causes for bugs.

Also the second loop's logic is kinda wrong. If the pan_ate's contents were increasing from the beginning to the end, the if condition is never triggered, because no element is bigger than the following one. If you want to get the highest element in the vector, you should instead check if pan_ate[u] is bigger than the current high and set high to be pan_ate[u] if it is. If you also change your loop to only run for u < pan_ate.size(), your code should run perfectly fine.

Lastly you can use iterators to loop through vectors or arrays (and prevent bothering with size()/length() functions):

std::vector<int> a(5);

for (int b : a) {
    /*Runs once for every element in a (5 times), element's value is stored in b*/
}

Upvotes: 1

Related Questions