Writing a for-loop?

This is what I need to do:

Write a for-loop that reads in 3 non-negative integers from the user (one at a time) and assigns the maximum value to a variable maxVal.

This is what I have, but I'm not sure how to execute the actual for-loop. Help would be greatly appreciated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  #include <iostream>
  using namespace std;

  int main()
  {
   int maxVal;
   int num1, num2, num3;
  
   cout<<"Enter an integer: ";
   cin>>num1;
 
   cout<<"Enter another integer: ";
   cin>>num2;

   cout<<"Enter one last integer: ";
   cin>>num3;

   for(
Firstly, and most obviously, you're disobeying the instructions you've been given, because you're not reading those values within the for loop.
You're thinking the wrong way. You only need one variable for the input, not 3. That's what the for-loop is for, to shorten the code. How for-loops work can easily be googled/youtubed for good explanations.

Decent video on how for-loops work -
https://www.youtube.com/watch?v=sBO8yvyyBI0&list=PLAE85DE8440AA6B83&index=22


Text tutorial on how they work -
http://www.tutorialspoint.com/cplusplus/cpp_for_loop.htm


Basically, you need a for-loop that runs 3 times.

1. Ask the user, save the input.
2. Assign it to a variable called MaxVal.
3. Ask the user, save the input (Using the same variable, you can overwrite it since it's saved in maxVal).
4. Check if it's bigger than maxVal, if it is, replace maxVal with what the user just inputted.
5. Repeat step 3-4.
Last edited on
So I would do something like this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 #include <iostream>
  using namespace std;

  int main()
  {
   int maxVal;
   int num;

   cout<<"Enter a non-negative integer: "<<endl;
   cin>>num

   cout<<"Enter another non-negative integer: "<<endl;
   cin>>maxVal

   for (maxVal > num; maxVal++;)
    cout<<"Maximum value = "<<maxVal<<endl;


I'm still not sure where everything is supposed to fit, even after reading the tutorial and reviewing my notes.
The first thing you need to do is make a for-loop that runs 3 times. That's not what you have done there. Look at the tutorial again, making the for-loop work correctly is the best first step you can take.

And like @MikeyBoy stated, your stuff needs to be inside the for loop. To me it sounds like you've still not understood the full concept of what a for-loop is used for, you can "c++ for loops" on google to find ton of more information and examples.
Last edited on
Topic archived. No new replies allowed.