while and for

Hi, it take me awhile to figure this out. But I don't get one thing. Why do I must use (for) to make it work? I tried to use while. It doesn't work at all.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
  #include "std_lib_facilities.h"

int main()

{

for (int i = 0;i<26;++i)
{

char ch = 'A' + i;
	
	cout << i << '\t' << ch << '\n';
	}
}
Last edited on
Show us the non-working while loop, can't help you much without seeing it.

Likely you tried to create the 'i' variable inside of your while loop which would reset it each time the loop iterates. move your counting variable above your while loop and it should work fine. Don't forget to iterate it inside the loop.

The two loops are basically the same only the for loop helps to manage your iterator variable.
Last edited on
1
2
3
4
5
6
7
8
int main(){
int i = 0;
while (i<26){
char ch = 'A' + i;
cout << i << '\t' << ch << '\n';
++i;
}
}
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
using namespace std;

int main(){
    int i = 0;
    while (i<26){
         i++; 
         char ch = 'A' + i - 1;
         cout << i << '\t' << ch << '\n';
    }
}


Edit;
Sorry, I've got to stop posting before testing. I was just trying to get the numbers to start at one instead of zero. I've just ran your original for loop and realised it also starts at zero so I'm just off the mark, sorry again.
Last edited on
@newbieg

Willo123 put it for me I guess. But I tried your. It work but missing A letter at first line and added ] at last line.
Topic archived. No new replies allowed.