-
What is wrong?
I need to fix each of these codes so that it will print numbers between 1 and 10. what is wrong?
Code:
#include <iostream>
using namespace std;
int main (void){
for (int n=1; n<=10; n++);
cout << n << endl;
return 0;
}
and
Code:
#include <iostream>
using namespace std;
int main (void)
{ n=1;
while (n<11)
cout << n << endl;
n++;
return 0;
}
any help would be appreciated, thanks
-
Code:
#include <iostream>
using namespace std;
int main () // void not necessary, but you can still put it there
{
for (int n = 2 ; n<10 ; n++) // no semi colon at end of for
cout << n << endl;
return 0;
}
Leave the other for you to do. If you meant you wanted to print between 0 and 11, then you should be able to change that easily.
-
Thanks for the help. Could you possibly explain why making the change is necessary? I'm new to programming, and am having some difficulty understanding what everything means.
thanks
-
well the symmantics of the for loop are as follows:
Code:
for ( int i = 0; i < 9; i++ ){
cout << i << endl;
}
the int i = 0 is setting the starting value for i to zero.
the i < 9 sets the upper limit of the counter, ie do whatever is in the braces until i is less than 9,
the i++ increments the i by 1 each time the loop is run
consequently the output for i will be
0
1
2
3
and so on till
8
hope this helps...you could also look into your book, or the cprogramming.com tutorials,
axon
-
well if this is the case, why are the two codes that i gave wrong?
Code:
#include <iostream>
using namespace std;
int main (void){
for (int n=1; n<=10; n++);
cout << n << endl;
return 0;
}
Code:
#include <iostream>
using namespace std;
int main (void)
{ n=1;
while (n<11)
cout << n << endl;
n++;
return 0;
}
why wouldn't these output the integers 1 through 10?
-
Quote:
Originally posted by girliegti
well if this is the case, why are the two codes that i gave wrong?
Code:
#include <iostream>
using namespace std;
int main (void){
for (int n=1; n<=10; n++);
cout << n << endl;
return 0;
}
Code:
#include <iostream>
using namespace std;
int main (void)
{ n=1;
while (n<11)
cout << n << endl;
n++;
return 0;
}
why wouldn't these output the integers 1 through 10?
The first is wrong because you have a semi-colon on the end of the for() line.
The second is wrong becuase the n++; line is not within the loop. As you have 2 lines of code that you want to run inside the loop, you must encase them with {}.
-
Ok, thank you. That makes a lot more sense.