Hello everyone. I am reading C++ Demystified and am on the chapter about the for loop. I am using this code

#include<iostream>
using namespace std;
 
int main()
{
int num, counter, total = 1;
cout << "Enter a number: ";
cin >> num;
cout << "The factorial of " << num << " is ";
 
for (int counter = 1; counter <=num; counter++)
total = total*counter;  
 
cout << total << endl;
 
return 0;
}

I am curious as to why the above code would work correctly and the code below does not

#include<iostream>
using namespace std;
 
int main()
{
 
int num, counter, total = 1;
cout << "Enter a number: ";
cin >> num;
cout << "The factorial of " << num << " is ";
 
for (int counter = 1; counter <=num; counter++)
total = counter; //change is here
 
cout << total << endl;
 
return 0;
}

Has the value of total been change from 1 somewhere? If not then how is

total*=counter

different from

total = counter

?

Recommended Answers

All 26 Replies

total = counter; //change is here

This is merely an assignment. It says "set total to the value of counter". Thus at the end of the loop "total" is equal to the number the user entered, not the factorial.

"*=" is really a short notation. For example:

total *= counter;

Is really this:

total = total * counter;

Basically it's multiplying itself by the value in counter.

Similar operators are +=, -=, and /=.

Hope this helps

Thanks. But what I mean is that at the beginning of the program the author set total to

total = 1

So why would

1*counter

be different than changing the value of counter to total?
i.e.

total = counter

(sorry. I am wording this the best I can)

Am I looking at this the wrong way?

total = 1

So why would

1*counter

be different than changing the value of counter to total?

It's actually not different. But when total equal to 1, you have to remember that that's only for the first iteration of the loop. After this assignment, total is equal to counter. The next iteration, total is no longer equal to counter, so the 1*counter is an incorrect assumption.

You could simply avoid the first iteration by adding some code before the loop, but doing so wouldn't make any sense (extra code and not really any optimization).

Thanks a lot. It just took me a little while to get what you were saying into my thick head. So in other words total is taking on a new value each time through the loop like this

Say I enter 5

total= total*counter

total = total(1)*1
total = total(1)*2
total = total(2)*3
total = total(6)*4
total = total(24)*5 = 120 (my final answer)

Correct. Loops always adds complication to the program, but makes the code shorter (much shorter).

Do you (or anyone reading) have any ides for a simple program I could work on that would give me practice in using the for loop. I have just started and I do not believe I have totally gotten a hold on using loops. I am still reading the same chapter in my book on for loops and I don't want to move on to while and do while before I am able to use the for loop without any problems. Thanks a lot for any help :)

Are you looking for a practice assignment? Here's one:

Write a program which will print all the pairs of prime numbers whose sum equals the number entered by the user.

Do you (or anyone reading) have any ides for a simple program I could work on that would give me practice in using the for loop. I have just started and I do not believe I have totally gotten a hold on using loops. I am still reading the same chapter in my book on for loops and I don't want to move on to while and do while before I am able to use the for loop without any problems. Thanks a lot for any help :)

Loops are difficult; I remember skipping them in the text book I was using to learn BASIC because I found them confusing. Eventually I found how hard it was not to use loops and tried to learn them. Once you learn loops in one programming language, the concept is the same for all programming languages.

Think of it this way:

  1. You've got the first section, which basically says how many times the loop will run.
  2. The next section is the code that repeats. You can find how many loops you've done already by using the iterator variable that you used earlier.
  3. The final statement says when the looping code ends. In C/C++, this is the '}'.

Of course, this all gets far more complex once you start nesting loops and using the iterator variables for all sorts of complex calculations. For now, don't worry about that, just concentrate on simple loops.

Some things for you to try:

  • Simple: Try creating a 2-dimensional array. Fill each row from 1 to 100.
  • Intermediate: Print out all the prime numbers from 1 to x.
  • Expert: Sort a list. (Maybe you shouldn't try this one now; it'll just confuse you ;))

Write a program which will print all the pairs of prime numbers whose sum equals the number entered by the user.

Wouldn't recommend this one to a complete beginner who is still figuring out how loops work...But still a good problem nonetheless.

I was thinking of starting a thread which will host practice problems of all levels (beginner to expert). I think its really a good idea since such things are not found on most forums and learning with practice is the best way to learn....

What do all you guys think ? Suggestions ?

Wouldn't recommend this one to a complete beginner who is still figuring out how loops work...But still a good problem nonetheless.

I was thinking of starting a thread which will host practice problems of all levels (beginner to expert). I think its really a good idea since such things are not found on most forums and learning with practice is the best way to learn....

What do all you guys think ? Suggestions ?

That is a FANTASTIC idea. The only thing is, a sample correct answer would have to be provided as well. As long as anyone who submits a problem is willing and able to provide an answer, this could be a really great thing.

I also have to point out that if such a thread were to be created, that there would be quite a number of newbies that would post their solutions to the thread, perhaps asking for help in writing a solution. So of course there'd be a bit more work for the moderation team.

But yeah, it sounds like a good idea...

[off topic mode on]

So of course there'd be a bit more work for the moderation team.

Agreed, but there are more people here who know how to write C/++, so it wouldn't all come down to the Mod's

Personally I think it's a great idea, such a thread could benefit the newbies which really want to learn programming instead of just getting a 'quick fix'.
Perhaps this could be placed in a new sub-categorie under 'tutorials'?


Niek

Hello there. *Update*

Sticky has been created -- feel free to post your own practice problems in the format followed in the sticky.

Thank you.

Hello there. *Update*

Sticky has been created -- feel free to post your own practice problems in the format followed in the sticky.

Boy, this forum really owes you, ~s.o.s~ (or should I say Sanjay).

Now I've got to put my thinking cap on... :twisted: (maybe I'll post some "brain teasers" tomorrow.)

Boy, this forum really owes you, ~s.o.s~ (or should I say Sanjay).

...whichever makes you happy, or should I say, is easier to type...;)

Now I've got to put my thinking cap on... (maybe I'll post some "brain teasers" tomorrow.)

Go Joey, go !!! :mrgreen:

Both samples work correctly, for a given definition of what the program should do...

...

  • Simple: Try creating a 2-dimensional array. Fill each row from 1 to 100.
  • Intermediate: Print out all the prime numbers from 1 to x.
  • Expert: Sort a list. (Maybe you shouldn't try this one now; it'll just confuse you ;))

I can't do the first yet because I have not learned anything on arrays.

The second on primes is what I attempted to do. I was able to write code that would list all from 2 - 100 within a few minutes. I am sure there are better ways to do this though. I also searched and searched and could not find a formula to find if a number is prime (after reading a few pages I found out that there isn't one yet). But anyway, here is what I did...

#include <iostream>
using namespace std;
 
int main()
{
int number;
 
cout << "Enter a number 1-100 to list all prime numbers below it: ";
cin >> number;
cout << endl;
 
if (number <= 1)
cout << "Numbers equal to or less than 1 are not prime numbers." << endl;
 
else
for (int x =2; x<= number; x++)
{
if (x==2 || x==3 || x==5 || x==7)
cout << x << endl;
else if (x%2!=0 && x%3!=0 && x%5!=0 && x%7!=0)
cout << x << endl;

}
 
cout << endl;
 
return 0;
}

Good job, you've almost got it...

But the program isn't very flexible because the numbers it divides by are hard-coded in. A better way to do it would be to have another loop inside it that checks to make sure that it isn't divisible by any of the numbers up until itself. If the remainder is 0, then it breaks and continues with the outer loop.

I hope you see what I mean.

Another thing you need to do is indent your code properly. Break the habit now of left-justified code because as you progress to larger programs, the bad habit will be harder to break and your code becomes unreadable very quicky.

It's also a good idea to use an editor which automatically indents your code, saving your the trouble. I find that Visual Studio's editor has an excellent auto-indent. It may not seem all that spectacular, but it was terribly useful when I was first learning C++, as whenever I forgot a semicolon at then end of a statement, the next line would auto-indent by one tab. I'd then realize my mistake, and fix it.

The editor I'm currently using (Xcode) doesn't work quite as nicely; it indents what the previous line was indented, so I have to do a lot of tabbing and deleting sometimes.

Sooo... the point I was trying to make was, get yourself a good editor and then you won't even need to worry about indentation, as the editor will do it for you.

The editor I'm currently using (Xcode) doesn't work quite as nicely; it indents what the previous line was indented, so I have to do a lot of tabbing and deleting sometimes.

Sooo... the point I was trying to make was, get yourself a good editor

Although I try not to proselytize too much, I've been a SlickEdit convert for almost a decade. When I find myself in situations without it, I find it amazing how much I've gotten used to it.

Thanks everyone. As far as indenting goes, I do. I use VC++ Express and it does it automatically. It's just that when I post my code on here I copy and paste and lose all indentation. Is there a way to make it keep all formating when posting here?

Code tags preserve all the indentation.

So if your code is indented, it should appear as it is in the browser window when you enclose it in code tags.

Also don't manually color your code, as you had done in your previous attempt. Just enclose the entire code in code tags, don't do anything else. It will automatically come out to be indented and highlighted.

Although I try not to proselytize too much, I've been a SlickEdit convert for almost a decade. When I find myself in situations without it, I find it amazing how much I've gotten used to it.

Thanks for the tip, Dave. I think I might try it when I can find some time.

And Sanjay is right, using code tags will preserve your identation. Anything else won't...

I am kind of stuck. Here is my loop so far

for (int x =2; x<=num; x++)
     {
     if (num%x++0)
        continue;
     else
        for (int y=1; y<=x; y++)
             {
             if (x%y==0)
                continue;
             else

I am stuck because I do not know exactly what to put in the else part of the second loop. I know that the loop should go like this:

outer loop | inner loop
2 | 2/1
.....2/2
3 | 3/1
.....3/2
.....3/3
4 | 4/1
.....4/2
.....4/3
.....4/4
and so on...

I just can't for the life of me figure out how to get the inner loop to complete its job. Am I even on the right track?

Hmm... you're getting there. Here's some pseudocode:

loop x from 2 to the number
   loop y from 2 to the number
      if x is divisible by y (and y is not x) then break out of the inner loop and tell user its not a prime
   end loop
end loop

I hope you get the idea.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.