Write python program for the sum of first n even numbers
Answers
Answered by
1
// C++ implementation to find sum of
// first n even numbers
#include <bits/stdc++.h>
using namespace std;
// function to find sum of
// first n even numbers
int evenSum(int n)
{
int curr = 2, sum = 0;
// sum of first n even numbers
for (int i = 1; i <= n; i++) {
sum += curr;
// next even number
curr += 2;
}
// required sum
return sum;
}
// Driver program to test above
int main()
{
int n = 20;
Proof:
Sum of first n terms of an A.P.(Arithmetic Progression)
= (n/2) * [2*a + (n-1)*d].....(i)
where, a is the first term of the series and d is
the difference between the adjacent terms of the series.
Here, a = 2, d = 2, applying these values to eq.(i), we get
Sum = (n/2) * [2*2 + (n-1)*2]
= (n/2) * [4 + 2*n - 2]
= (n/2) * (2*n + 2)
= n * (n + 1)
// C++ implementation to find sum of
// first n even numbers
#include <bits/stdc++.h>
using namespace std;
// function to find sum of
// first n even numbers
int evenSum(int n)
{
// required sum
return (n * (n + 1));
}
// Driver program to test above
int main()
{
int n = 20;
cout << "Sum of first " << n
<< " Even numbers is: " << evenSum(n);
return 0;
}
Output:
Sum of first 20 Even numbers is: 420
cout << "Sum of first " << n
<< " Even numbers is: " << evenSum(n);
return 0;
}
// first n even numbers
#include <bits/stdc++.h>
using namespace std;
// function to find sum of
// first n even numbers
int evenSum(int n)
{
int curr = 2, sum = 0;
// sum of first n even numbers
for (int i = 1; i <= n; i++) {
sum += curr;
// next even number
curr += 2;
}
// required sum
return sum;
}
// Driver program to test above
int main()
{
int n = 20;
Proof:
Sum of first n terms of an A.P.(Arithmetic Progression)
= (n/2) * [2*a + (n-1)*d].....(i)
where, a is the first term of the series and d is
the difference between the adjacent terms of the series.
Here, a = 2, d = 2, applying these values to eq.(i), we get
Sum = (n/2) * [2*2 + (n-1)*2]
= (n/2) * [4 + 2*n - 2]
= (n/2) * (2*n + 2)
= n * (n + 1)
// C++ implementation to find sum of
// first n even numbers
#include <bits/stdc++.h>
using namespace std;
// function to find sum of
// first n even numbers
int evenSum(int n)
{
// required sum
return (n * (n + 1));
}
// Driver program to test above
int main()
{
int n = 20;
cout << "Sum of first " << n
<< " Even numbers is: " << evenSum(n);
return 0;
}
Output:
Sum of first 20 Even numbers is: 420
cout << "Sum of first " << n
<< " Even numbers is: " << evenSum(n);
return 0;
}
Answered by
2
1. Make a variable to hold the running total
2. Iterate through each number less than or equal to n
- add each number you iterate through to the variable
3. return the sum variable
def sumFirstN(n):
sum = 0
for i in range(n+1):
sum = sum + i
return sum
print(firstN(10))n)
Note: you need "for i in range(n+1):" because range generates a list of numbers up to (but not including) n, so we need to pass it n+1 to include n
Similar questions