Interval

Hello, I need help guys. My instructor want one exam from me.

I need to do program which will:
Count only odd numbers from interval <a,b>
Border of interval will be specified from keyboard and then program print count of loaded values and sum these values.

For any help, thanks so much!
Here is how to do basic input/output - http://www.cplusplus.com/doc/tutorial/basic_io/

Take in a and b.

Run a for-loop that goes from a to b - http://www.tutorialspoint.com/cplusplus/cpp_for_loop.htm

use if-statements and modulus operator to find out if it is even or odd

http://www.cprogramming.com/tutorial/modulus.html
You can check if the number is odd or even using operator %
1
2
3
4
int number{...}; //some number

if(number % 2){ /*its odd number coz for example 7%2 == 1 */}
else {/*its even number coz for example 6%2 == 0*/}
You only need to check whether a is odd or even. If it is odd, leave it be, otherwise add 1. Then just loop in steps of 2 from a to b.
Well, it's kinda complicated for me. This is new curriculum what I am trying to learn, actually.
I did something, but it won't compile. Am I am on a good way? And what is bad? Thanks for your help!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;

int fNumb;
int sNumb;

int main()
{
	cout << "Enter first number to interval" << endl;
	cin >> fNumb >> endl;
	cout << "Enter second number to interval" << endl;
	cin >> sNumb >> endl;

	for(int a=fNumb; a>sNumb; a--)
{
	cout << "a= " << a << " number\n";	
}

system("PAUSE");
return 0;
}

Last edited on
I did something, but it won't compile.

Well, even if you don't understand the meaning of the error message, at least the compiler should tell you at which line and column it found an error. Use that as your starting point.

In this case it is the cin >> fNumb >> endl; Use endl only for output - example cout << endl;. Hence you need just cin >> fNumb; without the endl which the compiler doesn't know what to do with.

As a matter of good practice, you should avoid the use of global variables. In this case
1
2
int fNumb;
int sNumb;
- move those declarations inside the main() function.
Last edited on
Topic archived. No new replies allowed.