Help?

Jul 13, 2012 at 10:32pm
What does "for (int i=1; i<5; i++)" mean? I'm trying to make the user to print 5 integers and find large and small. Ignore the sum and product!

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
#include <iostream>
using namespace std;
int main()
{
int userIn, sum, product, small, large;
cout << "Enter 5 integers\n";
cin >> userIn;
sum=userIn;
product=userIn;
small=userIn;
large=userIn;

for (int i=1; i<5; i++) {
  cin >> userIn;
  sum=sum+userIn;
  product=product*userIn;
  if (userIn<small)
    small=userIn;
  if (userIn>large)
    large=userIn;
}

cout << "Sum: " << sum << endl;
cout << "Average: " << sum/5 << endl;
cout << "Product: " << product << endl;
cout << "Smallest: " << small << endl;
cout << "Largest: " << large << endl;
return 0;
}
Jul 13, 2012 at 10:41pm
closed account (zb0S216C)
DetectiveRawr wrote:
"What does "for (int i=1; i<5; i++)" mean?"

It's a loop. i is a variable that's local to the loop; it's initialised to 1. While the value of i is less than 5, i is incremented by 1 after the body of the loop is executed. It's equivalent to:

1
2
3
4
5
6
7
8
9
10
{
    int i_(1);
    while(i_ < 5)
    {
        /*
         * ...
         */
        ++i_;
    }
}

See here: http://www.cplusplus.com/doc/tutorial/control/#for

Wazzak
Last edited on Jul 13, 2012 at 10:43pm
Jul 13, 2012 at 11:57pm
Hmmm thank you. I haven't reach the part about loop yet. I'm at the beginning lol.
Jul 14, 2012 at 12:21am
closed account (zb0S216C)
It looks like you're rushing ahead of yourself. Slow down, son.

Wazzak
Jul 14, 2012 at 12:23pm
Is it really normal to declare a variable integer inside a for loop?
Jul 14, 2012 at 12:24pm
Is it really normal to declare a variable integer inside a for loop?

Yes.
Jul 14, 2012 at 12:26pm
closed account (zb0S216C)
Yes, but you don't have to declare anything either. In fact, you can declare any type of variable/object.

Wazzak
Jul 23, 2012 at 11:15pm
Well I learned about variables and now I"m at the control structure which is chapter 2.
Topic archived. No new replies allowed.