Help?

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;
}
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
Hmmm thank you. I haven't reach the part about loop yet. I'm at the beginning lol.
closed account (zb0S216C)
It looks like you're rushing ahead of yourself. Slow down, son.

Wazzak
Is it really normal to declare a variable integer inside a for loop?
Is it really normal to declare a variable integer inside a for loop?

Yes.
closed account (zb0S216C)
Yes, but you don't have to declare anything either. In fact, you can declare any type of variable/object.

Wazzak
Well I learned about variables and now I"m at the control structure which is chapter 2.
Topic archived. No new replies allowed.