954,506 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

For loop

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

?

Boldgamer
Light Poster
44 posts since Dec 2006
Reputation Points: 11
Solved Threads: 2
 
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

John A
Vampirical Lurker
Team Colleague
7,630 posts since Apr 2006
Reputation Points: 2,240
Solved Threads: 339
 

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?

Boldgamer
Light Poster
44 posts since Dec 2006
Reputation Points: 11
Solved Threads: 2
 
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).

John A
Vampirical Lurker
Team Colleague
7,630 posts since Apr 2006
Reputation Points: 2,240
Solved Threads: 339
 

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)

Boldgamer
Light Poster
44 posts since Dec 2006
Reputation Points: 11
Solved Threads: 2
 

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

John A
Vampirical Lurker
Team Colleague
7,630 posts since Apr 2006
Reputation Points: 2,240
Solved Threads: 339
 

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 :)

Boldgamer
Light Poster
44 posts since Dec 2006
Reputation Points: 11
Solved Threads: 2
 

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.

aniseed
Posting Whiz
359 posts since Apr 2006
Reputation Points: 48
Solved Threads: 7
 
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:You've got the first section, which basically says how many times the loop will run.
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.
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 ;))

John A
Vampirical Lurker
Team Colleague
7,630 posts since Apr 2006
Reputation Points: 2,240
Solved Threads: 339
 
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 ?

~s.o.s~
Failure as a human
Administrator
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 734
 
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.

PirateTUX
Junior Poster
101 posts since Jan 2007
Reputation Points: 17
Solved Threads: 3
 

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...

John A
Vampirical Lurker
Team Colleague
7,630 posts since Apr 2006
Reputation Points: 2,240
Solved Threads: 339
 

[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

Nick Evan
Not a Llama
Moderator
10,112 posts since Oct 2006
Reputation Points: 4,142
Solved Threads: 403
 

Hello there. *Update*

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

Thank you.

~s.o.s~
Failure as a human
Administrator
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 734
 

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.)

John A
Vampirical Lurker
Team Colleague
7,630 posts since Apr 2006
Reputation Points: 2,240
Solved Threads: 339
 
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:

~s.o.s~
Failure as a human
Administrator
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 734
 

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

jwenting
duckman
Team Colleague
8,392 posts since Nov 2004
Reputation Points: 1,662
Solved Threads: 337
 
...
  • 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>
usingnamespace 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;
}
Boldgamer
Light Poster
44 posts since Dec 2006
Reputation Points: 11
Solved Threads: 2
 

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.

John A
Vampirical Lurker
Team Colleague
7,630 posts since Apr 2006
Reputation Points: 2,240
Solved Threads: 339
 

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.

WaltP
Posting Sage w/ dash of thyme
Moderator
10,506 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You