"if" statement question

So, as you can see I don't have a whole lot of experience here (first thing I write in c++).
What I'm trying to do here is compare each number in the fib. sequence to each character in the "mergedChar" array, it'll go up from 'a' to 'b' if the number (in the sequence) is even, from 'b' to 'a' if odd. The only way I can think of doing is having A LOT of if statements (I don't think it's a good idea). How can I make this compare each one? Any other tips and changes are more than welcome. I'm doing this as practice.

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
    cout << "#: ";                          cin >> userInput;
    cout << "Password for encryption: ";    cin >> password;


    string mergedStr = userInput + password;  // Merge input text w/ password
    int strSize = mergedStr.size();           // Counts characters in string

    // Convert merged text from string to char
    char mergedChar[1024];  // Char Array
    strcpy(mergedChar, mergedStr.c_str());  // Copies mergedStr to mergedChar


    int range = strSize + 1;
    int Fib[range];

    for ( int i = 0; i < range; i++ )
    {
        if ( i <= 0 ) Fib[i] = i;
        else if ( i == 1 ) Fib[i] = 1;
        else Fib[i] = Fib[i - 1] + Fib[i - 2];
    }

    for ( int i = 1; i < range; i++)
        cout << "\n\nFib[" << i << "] = " << Fib[i];     // TEMPORARY (Just to show that it works)
        cout << "\n\nArray 7: " << Fib[5] << endl;       // TEMPORARY (Just to show that it works)



    // Change character if even or odd
    if (Fib[1] % 2 == 0)
        cout << static_cast<char>(mergedChar[0] + 1) << endl;
    else
        cout << static_cast<char>(mergedChar[0] - 1) << endl;
Last edited on
It's not necessary converting the std::string to a c-string.

I don't know what you mean by "having a lot 'if' - statements.
1
2
3
for (int i = 0; i < mergedStr.size(); i++ ) {
    cout << static_cast<char>(Fib[i] % 2  ?  mergedStr[i] - 1  :  mergedStr[i]+1)   << endl;
}

Is this what you want to do?
That worked, thanks a lot.
Last edited on
*edited
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

...
// If you want your own range (a shorter value):
int range;
std::cin >> range;
if (range < 0 || range > mergedStr.size()) range = mergedStr.size();
....

std::vector<int> fib_v(range);      // a vector is mostly like an array, but knows its size.
for ( int i = 0; < fib_v.size(); ++ i) {
   if ( i == 0 || i == 1) fib_v[i] = 1;    // omits the first fibonacci value
    else fib_v[i] = fib_v[i - 1] + fib_v[i - 2];
}
...

for (int i = 0; i < fib_v.size(); ++ i)    // here you have yet the 'right' values in fib_v[i]
{
    std::cout << static_cast<char>( fib_v[i] ? ++mergedStr[i] : --mergedStr[i] ) << std::endl;
}
Last edited on
Thanks for everything, i'll check it out.
Topic archived. No new replies allowed.