I've written a code to use a for loop to display all the even numbers with in the range based on the parameters inputted by the user. However, I'm a little confused as to why the i < b in the for statement still outputs b as the final number in the loop being that it isn't and <= symbol. Also if a is an even number it also populates in the output. I've tried using if (i % 2 == 0) && (i > a) as well as if (i % 2 == 0) && (i > a) with no avail.
Here is the code:
#include<iostream> #include<string> using namespace std; //Loop function to display even numbers within a range int print_even(int a, int b) { int i; for (i = a; i < b; i++) { if (i % 2 == 0) cout << i << " "; } return i; } //main function int main() { int a, b; cout << "Write the initial number" << endl; cin >> a; cout << "Write the ending number" << endl; cin >> b; cout << "These are all the even integers between the initial and ending numbers" << endl; cout << print_even(a,b); return 0; } Here is the output:
Write the initial number 2 Write the ending number 60 These are all the even integers between the initial and ending numbers 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 Any feedback would be greatly appreciated!
4, and use a debugger to step through your code statement by statement.returnandcoutactually is.print_evenreturn a number? Think about what it returns and what you do with the returned value.