for loop

Jun 24, 2012 at 3:35am
can someone tell me the for loop for this one?

11, 22, 43, 74, 511

i try

1
2
3
4
5
for( int y=11, x=11;x<=51 && y<=115 ; y=y+x, x=x+10)
{
cout<<y;
cout<<", ";
}


but it result to 11, 22, 43, 74, 115
now my prof want it to be 511... can someone tell me how?!
Jun 24, 2012 at 9:35am
So you want to continue the series until 511 right? I think thats what you mean.

Which part of the for loop controls when it stops? Is it right?

Can you think of a better way to write this? Hint put all the calculations involving y in the body of the loop and not in the end condition or increment expression.

Hope this helps.

TheIdeasMan
Jun 29, 2012 at 4:25pm
i had figure this out. my next question is..
how could i possibly get EACH number input of the for loop??

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
using namespace std;

main()
{
	
	int numofinput;
	

	do{
	cout<<"How many input you like? ";
	cin>>numofinput;
	


	if (numofinput>0 && numofinput<=10)
	{
	

		for (int x=1; x<=numofinput; x++)
		{
			cout<<"\nInput number: ";
			cin>>number;
		}
		


	}
	else
	{
		cout<<"Invalid input!\n";
		system ("pause");
}}while (numofinput<=0 || numofinput>10);
}
Jun 29, 2012 at 6:26pm
Hi yhangel,

I think you should stick to the for loop because it's easier to test for the end condition. Abandon the code you have - it's the wrong approach.

This series only needs 2 numbers to start it off, and you would like another number to specify when the series stops.

I also think you should do a basic design:

Start with a blank file, write comments that specify how you are going to do the problem, like this:

1
2
3
4
5
6
//get first number in the series
//get second number in the series
//get the end number of the series

//use a for loop to calc & print each number in the series up to the end number


then decide what variables and functions you need. You may not need any functions.

Go back and write the code you need, leave the comments they are documentation.

Anther thing - get used to starting with zero not 1, like this:

1
2
3
4
for (int x=0;  x < EndNumber; x++)  {  //hint you will have 2 variables on this line
//do stuff EndNumber times
}


Hope this helps
Jun 30, 2012 at 7:36am
the only problem i have is how to convert pointer of C++ to java
Jun 30, 2012 at 9:58am
maybe it's a little bit difficult... btw, if you have anything to ask about java, go to java-forums.org/forum.php
Topic archived. No new replies allowed.