November 16th, 2004, 01:08 AM
|
#1 (permalink)
| | Member
Join Date: Nov 2004
Posts: 56
|
i'm writing a simple for loop for extra credit. it is supposed to print to the screen only the even numbers from 2 - 100. this is what i have and it is infinite looping. i'm using dev c++ version 4.0.
#include <iostream.h>
#include <stdlib.h>
int main()
{
int num;
for(num=2;num<=100;num+2)
{
cout << num <<"\n";
}
system("PAUSE");
return 0;
}
help is appreciated,
thanks
sirhc |
| |
November 16th, 2004, 01:20 AM
|
#2 (permalink)
| | Senior Member
Join Date: Aug 2004 Location: LA, California
Posts: 808
|
Try this: Code: #include <iostream.h>
#include <stdlib.h>
int main()
{
int num;
for(num=2;num<=100;num+=2)
{
cout << num <<"\n";
}
system("PAUSE");
return 0;
} Did you want it to loop?
Remember in c++ you have to put the += together if you are adding numbers together (proper syntax).
__________________
People are like coins, there's always two sides.
Last edited by TechKnickle : November 16th, 2004 at 01:24 AM.
|
| |
November 16th, 2004, 02:21 AM
|
#3 (permalink)
| | Member
Join Date: Nov 2004
Posts: 56
|
no it was not supposed to loop, thanks that was perfect. let me ask you though, why does it have to be +=, it works, but how? |
| |
November 16th, 2004, 02:30 AM
|
#4 (permalink)
| | Senior Member
Join Date: Aug 2004 Location: LA, California
Posts: 808
|
Yeah, sure no problem.
In c++, the '+' (unary) by itself effectively does nothing. Same concept with the '-', but this does something, it doesn't subtract though. It negates your statement (the value entered or computed earlier).
+= is an assignment operator, telling the computer "this needs to be done, so do it now".
Basically. |
| |
November 16th, 2004, 03:15 AM
|
#5 (permalink)
| | Ultimate Member
Join Date: Oct 2001 Location: Illinois
Posts: 2,959
|
basically what you had was a temporary statement: add 2 to num and continue. += says: add 2 to num and store the result as num. |
| |
November 17th, 2004, 02:20 PM
|
#6 (permalink)
| | Ultimate Member
Join Date: Sep 2003 Location: Philadelphia
Posts: 1,462
|
"num+=2" means "num=num+2" |
| | |
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | | |
Posting Rules
| You may post new threads You may post replies You may not post attachments You may not edit your posts HTML code is Off | | | | Most Active Discussions | | | | | Recent Discussions  | | | | | |