Determine the sum of even numbers

Determine the sum of the even numbers between 1 and n. n is specified by the user.
Example:
If the user enters 16, compute the sum of 2 + 4 + 6 + …16
If the user enters 21, compute the sum of 2 + 4 + 6 + …18 + 20

n = number
l = limit number
r = result

Here is my code

#include<iostream>
using namespace std;
int main(){
int n = 0;
int l = 0;
int r;

cout<<"\nEnter the limit number: ";
cin>>l;

while(n < l){
n = n + 1;
}
cout<<"\nResult: "<<r<<endl;
return 0;
}

I don't know how to make the summation 2 + 2 + 2 ...+∞
It just appear the number plus two but not the secuency
Also it has to be only with "while".
Help please :c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

int main()
{
   int n { };

   std::cout << "Enter n: ";
   std::cin >> n;
   std::cout << '\n';

   int sum { };

   for (int i { 2 }; i <= n; i += 2)
   {
      sum += i;
   }

   std::cout << "The sum: " << sum << '\n';
}
I've already fixed it :DDD

#include<iostream>
using namespace std;
int main(){
int n = 0;
int l = 0;
int r;

cout<<"\nEnter the limit number: ";
cin>>l;

while(n < l){
n = n + 1;
n++;
r = r + n;
}
cout<<"\nResult: "<<r<<endl;
return 0;
}
Er, math, dudes.

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
#include <iostream>
#include <string>

int main( int argc, char** argv ) try
{
  auto n = std::stoll( argc == 2 ? argv[1] : "x" );
  
  auto is_negative = n < 0;
  if (is_negative) n = -n;
  
  n /= 2;           // n ← number of even integers in [1,n]
  n = n * (n + 1);  // n ← sum of first n even integers
  
  if (is_negative) n = -n;
  
  std::cout << n << "\n";
}
catch (...)
{
  std::cout << 
    "You must supply as argument an integer N.\n"
    "Prints the sum of all even integers in [1,N].\n"
    "N may be negative.\n";
  return 0;
}
$ a --help
You must supply as argument an integer N.
Prints the sum of all even integers in [1,N].
N may be negative.

$ a 10
30

$ a -10
-30

$ a 0
0

$ a 1
0

$ a 2
2

$ a 3
2

$ a 4
6

$ a 5
6

$ a 6
12

$ a -1234567890
-381039469372046970

$ a 1234567890
381039469372046970

Topic archived. No new replies allowed.