#### Archived

This topic is now archived and is closed to further replies.

## Recommended Posts

Ok, I have been following the C++ Primer Plus exercises, and I was going fine until I got to chapter 5, in which one of the exercises says to take two interger values and add them and all the integers in between together. Now, whenever I compile my code, the final answer is somewhere in the range of -8,000,000 to -9,000,000. Here is the code...

#include <iostream>
using namespace std;

int main()
{
int x, y;
int sum;

cout<<"Enter an integer...\n";
cin>>x;
cout<<"\nEnter another integer...\n";
cin>>y;

for (int i = x; i < y; i++)
{
int count = 0;
sum += (x + count);
count++;
}

cout<<"\n\n"<<sum<<"\n\n";

return 0;
}


I can''t figure out what is wrong, and it is beginning to piss me off Anyways, please help...

##### Share on other sites

  int x=0,y=0;int sum =0;cin >>x;cin >>y;for (int i =min(x,y);i<max(x,y);i++{    sum += i;}cout << sum;

This should do it.

##### Share on other sites
You should initialize sum to 0 (int sum = 0 or else it will contain garbage. You don''t have to do this with x or y because their values are reassigned with user input.

##### Share on other sites
Well, for starters, your program won't work if x > y

There really should be an easier way to do this...but I'm tired right now (running a fever), and I can't wrap my mind around that for loop ya got there.

Maybe somethin like:

      # blah blahint x, y, sum = 0;cout << "number please \n";cin >> x;cout << "godammit gimme another number \n";cin >> y;if (x<y){   sum = x;    while (x<y)       {          x++;          sum += x;       }}else{  sum = y;   while (y<x)      {        y++;        sum += x;      }}cout << sum;return 0;

Holy shit, that's bad code. I don't even know if it works. I'm going to bed.

*500 error*

EDIT: Jonbca's got it. I completely forgot about the min and max functions. Back to fundamentals for me.

EDIT AGAIN: Fixed my code. Jonbca's is much nicer to read, though.

[edited by - andromeda on September 30, 2002 10:44:02 PM]

[edited by - andromeda on September 30, 2002 10:45:00 PM]

[edited by - andromeda on September 30, 2002 10:47:19 PM]

[edited by - andromeda on September 30, 2002 10:52:58 PM]

##### Share on other sites
You got your loop wrong...should be something like this

you want to have the user enter two integers and return the sum from the first integer, and every integer in between the second integer entered

  int x,y;        // First and second integer enteredint sum = 0;    // Make sure to set sum to 0for( int i = x; i < y+1; i++ )   sum += i;

The problem your having first off is that sum contains garbage because you never initialized it to 0. Most likely why you getting those weird values.

Second error is the use of "count" in your code. Each iteration your setting it to 0, thus basically adding 0 each loop to x which is always going to be the first integer entered....so sum is going to equal whatever garbage value + x for each loop iteration.

Third error is you for condition, it should be i < y+1 and not i < y as this would cause premature exit of the loop without adding in the value of y, and we want up/to and including y

Let me give ya an example of test values using my loop. Here we go

When we come to the for loop x and y will hold the integer values
(say 3,5 ..keep it short ) and sum will have been set to 0, so that it records a valid sum.

Once we enter the for loop:

1st Iteration -
the variable i gets initialized to x''s value ( so i == 3 ) and
i will be less then 6 so the condition holds
sum will become sum = 0 + 3 ( writing it like sum = sum + i )
sum will equal 3 at the end of this iteration
i will be incremented to now equal 4

2nd iteration -
i will be less then 6
sum will become sum = 3 + 4
sum will equal 7 now
i will be incremented to 5

3rd iteration -
i will be less hten 6
sum will become sum = 7 + 5
sum will equal 12 now
iwill be incremented to 6

4th iteration -
i is NOT less then 6 and we fall out of the loop

This might be a bit long I apologize, but I hope it helps ya understand loops a bit better

Synapse

##### Share on other sites
Thanks a lot everyone, especially Synapse, for making it so clear. The code you gave works perfectly... if x < y. But when y < x, it returns 0. Is there a fix for this (I think i can figure it out, but just to be sure...)?

Also, what header file does min() and max() use?

[edited by - PepsiPlease on September 30, 2002 11:03:44 PM]

##### Share on other sites
My code does not take into account which integer is larger, but Jonbca''s loop takes care of that...

Synapse

##### Share on other sites
Actually, I got it too...

  #include <iostream>using namespace std;int main(){	int x, y;	int sum = 0;	cout<<"Enter an integer...\n";	cin>>x;	cout<<"\nEnter another integer...\n";	cin>>y;		if (x < y)	{		for (int i = x; i < y + 1; i++)			{							sum += i;				}	}	if (y < x)	{		for (int i = y; i < x + 1; i++)		{			sum += i;		}	}	cout<<"\n\n"<<sum<<"\n\n";		return 0;}

##### Share on other sites

Not sure what header they r in really...you could write them yourself easy enough...

int MAX( int a, int b ) { return a > b ? a : b; }
int MIN( int a, int b ) { return a < b ? a : b; }

##### Share on other sites
C++ Primer Plus is a book for people who have programed before. Its not really a beginners book. I have C++ Primer Plus, and I had a problem with the same question, but I solved it myself. You should get a book on C also. Arrays, Loops, Pointers, functions are all C stuff, and C books do a good job of explaining this features. Actually you should master them. You need to get a book that explains everything, and more up to date book. Keep C++ Primer Plus the author writes very well, but he assumes you know a lot because its not a beginners book, but get a beginners book also. Someone told me its good to have several books, because one author may explain something better than another. Not many people can explain all of C++ effectively.

##### Share on other sites
Tune up your compiler''s warning level. VC6 above should give a ''variable used without being initialized'' or something like that on the code (dunno about other compilers).

##### Share on other sites
I would also make your count var a double. Or a long int. As if you add up all the things inbetween 0 and max(int) you will wrap.

##### Share on other sites
And of course the sum var too. In any case I would make x and y shorts instead if allowed

##### Share on other sites
quote:
Original post by Cmutt1974
C++ Primer Plus is a book for people who have programed before. Its not really a beginners book. I have C++ Primer Plus, and I had a problem with the same question, but I solved it myself. You should get a book on C also. Arrays, Loops, Pointers, functions are all C stuff, and C books do a good job of explaining this features. Actually you should master them. You need to get a book that explains everything, and more up to date book. Keep C++ Primer Plus the author writes very well, but he assumes you know a lot because its not a beginners book, but get a beginners book also. Someone told me its good to have several books, because one author may explain something better than another. Not many people can explain all of C++ effectively.

Actually, I have been learning C for awhile now... about 6 months. The only problem is that I had not had a book, so I was trying to learn from th many poorly constructed online tutorials that, for the most part, just say: this (*) is a pointer. Use it. I bought this book (along with aquiring a few other older books) to increase my learning and get my C++ programming off the ground.

##### Share on other sites
quote:
Original post by Cmutt1974
C++ Primer Plus is a book for people who have programed before. Its not really a beginners book. I have C++ Primer Plus, and I had a problem with the same question, but I solved it myself. You should get a book on C also. Arrays, Loops, Pointers, functions are all C stuff, and C books do a good job of explaining this features. Actually you should master them. You need to get a book that explains everything, and more up to date book. Keep C++ Primer Plus the author writes very well, but he assumes you know a lot because its not a beginners book, but get a beginners book also. Someone told me its good to have several books, because one author may explain something better than another. Not many people can explain all of C++ effectively.

Actually, I have been learning C for awhile now... about 6 months. The only problem is that I had not had a book, so I was trying to learn from th many poorly constructed online tutorials that, for the most part, just say: this (*) is a pointer. Use it. I bought this book (along with aquiring a few other older books) to increase my learning and get my C++ programming off the ground.

##### Share on other sites
Ok, one more question now...

How do you dynamically create a new array of structures?

Here is what I did...

        struct car   //The structure car{	char make[20];	int year;};//...car * cars[numcars] = new car; //create array of structures  //Whenever I try this it compiles fine, but then upon execution just skips the whole program and goes to the end. //Anyway, here is the full code:            #include <iostream>using namespace std;int main(){	int numcars = 0;	struct car 	{		char make[20];		int year;	};	cout<<"How many cars do you wish to catalog? ";	cin>>numcars;		car * cars = new car[numcars];	for (int a = 0; a < numcars; a++)	{		cout<<"\nCar #"<<a + 1<<":\n";		cout<<"Please enter the make: ";		cin.getline(cars[a].make, 20);		cout<<"\nPlease enter the year: ";		cin>>cars[a].year;	}	cout<<"\n\nHere is your collection: \n";	for (int b = 0; b < numcars; b++)	{		cout<<cars[b].year<<" "<<cars[b].make<<endl;	}	delete [] cars;	return 0;}

Don't laugh... I'm sure I have plenty of errors in there.

Edit: Now the program runs smoothly, except it skips the part to enter in the make - it just goes straight to the year.

[edited by - PepsiPlease on October 2, 2002 7:26:51 PM]

[edited by - PepsiPlease on October 2, 2002 7:33:12 PM]

[edited by - PepsiPlease on October 2, 2002 7:35:06 PM]

• ### Forum Statistics

• Total Topics
628341
• Total Posts
2982175

• 9
• 24
• 9
• 9
• 13