sum of odd numbers between 2 integers

Hey guys,

I have an assignment for practice with for loop. I'm extremely new to c++ world and any help for this assignment is much appreciated.

Assignment states that:

Both numbers must be positive
First number must be less than the second

Cases First Odd: Start with this value
Ex: Valid user input: 3, 13. Ouput 3+5+7+9+11+13 = 48
First Even: Start with the next value
Ex: Valid user input: 4, 13. Output 5+7+9+11+13 = 45

I know how to set the numbers to be positive but I'm kinda struggling with the rest. Again, Any help is much much appreciated!
Last edited on
closed account (18hRX9L8)
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/* Usandfriends */
#include <iostream>

int main(void)
{
	int low,high,num,total;
	
	std::cout<<"This program prints the odd numbers between two positive numbers and the total sum."<<std::endl;
	while(true)
	{
		std::cout<<"First number?  ";
		std::cin>>low;
		std::cin.ignore();
		if(low>=0)
		{
			break;
		}
		std::cout<<"The numbers have to be positive."<<std::endl<<std::endl;
	}
	while(true)
	{
		std::cout<<"Second number?  ";
		std::cin>>high;
		std::cin.ignore();
		if(high>low)
		{
			break;
		}
		std::cout<<"The number has to be greater than "<<low<<"."<<std::endl<<std::endl;
	}
	
	if(low%2==0)
	{
		low++;
	}
	
	std::cout<<low<<" + ";
	total=num=low;
	
	while(num<high-2)
	{
		num=num+2;
		std::cout<<num<<" + ";
		total+=num;
	}
	
	if(high%2!=0)
	{
		total+=high;
		std::cout<<high<<" = "<<total;
	}
	else
	{
		std::cout<<"\b\b\b = "<<total;
	}
	
std::cin.ignore();
return(0);
}
Last edited on
thanks a bunch!
Topic archived. No new replies allowed.