program code help

What I'm most confused by is where I put the "while" and "int" statements. I think I have them in the wrong places.
Secondly, I don't know how to make the program use the input numbers to do the calculation.

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

int main()
{
    std::cout << "Enter two numbers: ";
    std::cout << std::endl;
    int v1 = 0, v2 = 0;
    std::cin >> v1 >> v2;
    int sum = 0, val = v1;
    while (val <= v2) {
        sum += val;
        ++val;
    }
    std::cout << "The sum of " << v1 << "to " << v2 << "inclusive is: ";
    std::cout << std::endl;
    return 0;
}


Last edited on
Looks ok to me. Only issue is that if v2< v1, the program wouldn't enter the while loop. You could restructure your variable declarations, if you wanted. Here's an example, but yours work fine.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

#include <iostream>

int main()
{
      std::cout << "Enter two numbers: " << std::endl; 
      int v1 = 0, v2 = 0, sum = 0, val;
      std::cin >> v1 >> v2;
      val = v1;
      while(val <= v2) {
            sum += val;
            ++val; //could also do val++
         }
      std::cout << "The sum of " << v1 << " to " << v2 << " inclusive is: "; //added some spaces
      std::cout << std::endl;
      return 0;
}
Last edited on
Hey thanks for the reply!

I found out that the reason it didn't work was because I forgot to add the "<< sum;" after "<< inclusive is: ".

It works now!

Hey I like the way you wrote the program! Looks more efficient!

Question:
Isn't it better practice to write:

std::cout << "Enter two numbers: ";
std::cout << std::endl;

considering you used that method at the bottom of your code? I know it's the same thing, but as a newbie it's good for consistency right?

Thanks!
considering you used that method at the bottom of your code? I know it's the same thing, but as a newbie it's good for consistency right?


Yes! Consistency is better. I was manually typing out the last couple lines of your code and missed that. I think one line looks better, but it's really up to you. I usually have using namespace std; at the top of my code so I don't have to worry about typing std:: every time I want to use something in the standard library. Although, I've heard differing opinions on that being a good practice.
Topic archived. No new replies allowed.