Sum of First N Odd Numbers
Add up the first n odd numbers using a loop.
Sample input
5
Sample output
25
Solution
n = 5
total = 0
for i in range(n):
total += 2 * i + 1
print(total)
const n = 5;
let total = 0;
for (let i = 0; i < n; i++) {
total += 2 * i + 1;
}
console.log(total);
public class Main {
public static void main(String[] args) {
int n = 5, total = 0;
for (int i = 0; i < n; i++) {
total += 2 * i + 1;
}
System.out.println(total);
}
}
fun main() {
val n = 5
var total = 0
for (i in 0 until n) {
total += 2 * i + 1
}
println(total)
}
let n = 5
var total = 0
for i in 0..<n {
total += 2 * i + 1
}
print(total)
void main() {
int n = 5, total = 0;
for (var i = 0; i < n; i++) {
total += 2 * i + 1;
}
print(total);
}
#include <iostream>
using namespace std;
int main() {
int n = 5, total = 0;
for (int i = 0; i < n; i++) {
total += 2 * i + 1;
}
cout << total << endl;
return 0;
}
#include <stdio.h>
int main() {
int n = 5, total = 0;
for (int i = 0; i < n; i++) {
total += 2 * i + 1;
}
printf("%d\n", total);
return 0;
}