Using two different data types in for statement

Hello, i'm on an exercise in Programming: Principles and practices using c++. I've tried many different things but i just can't get this for statement to work.

The exercise is to produce the alphabet a-z with the equivalent numbers next to it (starting from 97) separated by a tab like so:

a 97
b 98
.....
y 121
z 122

I've already done this program using a while loop and its working perfectly the next exercise is to do it using a for loop. This is the most logical way i can put it but it still isn't work, as always your help is appreciated!!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

using namespace std;

int main (){


// l stands for letter
// n represents number

    for (int n = 97; char l = a; n<123; ++n, ++l) {
        cout << l << '\t' << n << "\n";

    }


}


The errors im getting:

In function 'int main()':|
warning: for increment expression has no effect [-Wunused-value]|
error: expected ')' before ';' token|
warning: unused variable 'l' [-Wunused-variable]|
error: name lookup of 'n' changed for ISO 'for' scoping [-fpermissive]|
note: (if you use '-fpermissive' G++ will accept your code)|
error: 'l' was not declared in this scope|
error: expected ';' before ')' token|
error: expected declaration before '}' token|
||=== Build finished: 5 errors, 2 warnings (0 minutes, 0 seconds) ===|



Last edited on
You have several approaches provided that letters follow sequentially incrementing their values by 1.

for example

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>

using namespace std;

int main ()
{
    for ( char c = 'a'; c <= 'z'; c++ ) 
    {
        cout << c << '\t' << ( int ) c << "\n";
    }
}



Or

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>

using namespace std;

int main ()
{
    for ( int n = 97; n < 123; n++ ) 
    {
        cout << ( char )n << '\t' << n << "\n";
    }
}



EDIT: As for using two different types in one for statement then you can do for example the following way

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>

using namespace std;

int main ()
{
    for ( char c = 'a'; int n = 123 - c; c++ ) 
    {
        cout << c << '\t' << 123 - n << "\n";
    }
}

Last edited on
Worked perfect once again, vlad. Thanks !!
Please, see my changes in the previous message.:)
Topic archived. No new replies allowed.