if/else in for loop

#include <iostream>
#include <cstdio>
#include<string>
using namespace std;

//I'm new to c++ and I feel incredibly dumb for this but this program isn't working whenever I run it it prints "eight" and "nine" to the console but instead of also printing even and odd it shows this 1�I��^H��H���PTI���
@.

//This program is meant to take input numbers a and b then count from a to and if it is less than 10 output the number as it's spelled. If it's greater output whether it's even or odd.

int main() {
int a, b;
cin >> a >> b;
string num_spell[] = {"one \n", "two \n", "three \n", "four \n", "five \n", "six \n", "seven \n", "eight \n", "nine \n"};
for(int i = a-1; i < b; i++){
if(i < 10){
cout << num_spell[i];
}else if(i > 9){
if(i % 2 == 0)
cout << "even";
}else{
cout << "odd";
}
}
return 0;
}
Are you required to use the for loop to count the numbers from a to b? Do you have the full instructions of your program or is it only what you mentioned above?

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
#include <iostream>
#include <string>
#include <cmath> // To use the abs() operator.

int main()
{
    int a{ 0 }, b{ 0 };
    std::string num_spell[] = { "one \n", "two \n", "three \n", 
	   "four \n", "five \n", "six \n", "seven \n", 
	   "eight \n", "nine \n" };

    std::cout << "Input two numbers\n";
    std::cin >> a >> b;

    // Count from a to b.
    int count = a - b;
    count = abs(count); //Use the absolute value and defined the variable to determine the count between 2 numbers.

    // If it is less than 10, then output the number as it's spelled.
    if (count < 10)
	   std::cout << num_spell[count - 1];

    // If it is greater, then output wheter it's even or odd.
    else if (count > 9)
    {
	   if (count % 2 == 0)
		   std::cout << "Even\n";

	   else
		   std::cout << "Odd\n";
    }

    return 0;
}
Last edited on
instead of also printing even and odd it shows this 1�I��^H��H���PTI���
@.

That's an out-of-bounds array access. Array num_spell[] has nine elements. The valid subscripts for that array are 0 to 8. Your code attempts to use num_spell[9] which is the tenth element - it is outside the array.
Topic archived. No new replies allowed.