Welcome to HBH! If you had an account on hellboundhacker.org you will need to reset your password using the Lost Password system before you will be able to login.

C++ for loop


ghost's Avatar
0 0

i am new to C++ and i know it alot like php but i cant a php for loop to work eiter this is what i have and the counle retunes 15.

#include <iostream>
#include <string>

using namespace std;

int main(int argc, char *argv[])
{
    int x = 0;
    int i;
    for (i = 1; i <= 5; i++)
    {
    x += i;    
    } 
    cout << x << endl;
    system("PAUSE");
    return EXIT_SUCCESS;
}

plz help me or is it soppose to do this i think the output should be 1 2 3 4 5 zer0pain


ghost's Avatar
0 0

Check out this link and the rest of their tutorial, it is very good and will help you a lot when you first start C++.


ghost's Avatar
0 0

I know the topic is a bit old but not to bad (bout a month)

Ok, first lets clean up the code a bit. I got ride of some extra stuff and took out the declaration of "int i" since you can do that in the for loop.

#include <cstdlib>
#include <iostream>
#include <string>

using namespace std;

int main()
{
int x = 0;

for (int i = 1; i <= 5; i++)
{
x += 1;
}
cout << x << endl;
system("PAUSE";
return EXIT_SUCCESS;
}

Now to get it to display the x variable everytime the loop runs thru we need to put the cout statement inside the loop. As of right now it will only execute the cout statement once the for loop is finished. So this finished code should work for you.

<also got rid of some un-needed stuff and commented a little.

#include &lt;iostream&gt; //no need to included irelevant headers

using namespace std;

int main() //just plain old main() will work just fine ; )
{
int x = 0;
for (int i = 1; i &lt;= 5; i++)
{
x += 1; //just add 1 or else it will be 1,3,6,etc
cout &lt;&lt; x &lt;&lt; endl;
}

system(&quot;PAUSE&quot;);
}

If you have any other questions i'm free for any help you or anyone else needs.( in C++ anyway =) )

Again sorry if i'm bringing out the dead a bit.

BTW hey all! Nice site.


ghost's Avatar
0 0

ThVoidedLine wrote:

……

#include &lt;iostream&gt; //no need to included irelevant headers

using namespace std;

int main() //just plain old main() will work just fine ; )
{
int x = 0;
for (int i = 1; i &lt;= 5; i++)
{
x += 1; //just add 1 or else it will be 1,3,6,etc
cout &lt;&lt; x &lt;&lt; endl;
}

system(&quot;PAUSE&quot;);
}

If you have any other questions i'm free for any help you or anyone else needs.( in C++ anyway =) )

Again sorry if i'm bringing out the dead a bit.

BTW hey all! Nice site.

Or.. instead of doing x += 1; you could use the increment operator -_- and just do x++; and it's always good practice to use the pre-increment operator when looping so change i++; to ++i; it's not so important when just using integers, but when you are messing with classes it creates an un-necessary temporary object.