Algorithm
Sum of Consecutive Odd Numbers I
Adapted by Neilor Tonin, URI Brazil
Read two integer values X and Y. Print the sum of all odd values between them.
Input
The input file contain two integer values.
Output
The program must print an integer number. This number is the sum off all odd values between both input values that must fit in an integer number.
Sample Input | Sample Output |
6 |
5 |
15 |
13 |
12 |
0 |
Code Examples
#1 Code Example with C Programming
Code -
C Programming
#include <stdio.h>
int main()
{
int x, y, tmp = 0, i;
int min, max;
scanf("%d%d", &x,&y);
if(x < y) {
min = x;
max = y;
} else {
max = x;
min = y;
}
for(i = (min + 1); i < max; ++i)
{
if(i % 2 == 1 || i % 2 == -1){
tmp += i;
}
}
printf("%dn", tmp>;
return 0;
}
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with C++ Programming
Code -
C++ Programming
#include <iostream>
using namespace std;
int main()
{
int x, y, tmp = 0;
int min, max;
cin >> x >> y;
if(x < y) {
min = x;
max = y;
} else {
max = x;
min = y;
}
for(int i = (min + 1); i < max; ++i)
{
if(i % 2 == 1 || i % 2 == -1>{
tmp += i;
}
}
cout << tmp << endl;
return 0;
}
Copy The Code &
Try With Live Editor
Input
Output
#3 Code Example with Java Programming
Code -
Java Programming
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int X, Y, total = 0;
Scanner input =new Scanner(System.in);
X = input.nextInt();
Y = input.nextInt();
if (X > Y) {
for (int i = X - 1; i > Y; i--) {
if (i % 2 != 0) {
total += i;
}
}
} else {
for (int i = Y - 1; i > X; i--) {
if (i % 2 != 0) {
total += i;
}
}
}
System.out.print(total+"n");
}
}
Copy The Code &
Try With Live Editor
Input
#4 Code Example with Python Programming
Code -
Python Programming
X = int(input())
Y = int(input())
start = min(X,Y)+1
end = max(X,Y)
if start % 2 == 0:
start += 1
sum = 0
for i in range(start, end, 2):
sum += i
print(sum)
Copy The Code &
Try With Live Editor
Output