Lets go a step back...
A typical for loop looks like this (for details I refer you to cppreference):
for ( init; condition; increment) {
loop-body
}
and is equivalent to:
{
init;
while(condition) {
loop-body
increment
}
}
Everything you put in the loop body will be executed repedeatly until the condition is false
(ie while
it is true
). For example in
for (int i= start; i < stop; ++i) foo(i);
the function foo
will be called (stop-start)
-times.
Your code
To see what your code is actually doing you can add some cout
s
int main() {
for(int i=33; i<=47 ;i++){
for(int j=58; j<=64;j++){
for(int z=91; z<=96;z++){
std::cout << "i = " << i;
std::cout << "j = " << j;
std::cout << "z = " << z;
}
}
}
}
or use a debugger.
Nested Loops
To be clear: You do not need to nest the loops in your code and (nested) loops are not something desireable in general. That being said, just a random example where you could use a nested loop is to print a rectangle of *
int height = 5;
int width = 5;
for (int i=0; i<height; ++i) {
for (int j=0; j<width; ++j) {
std::cout << "*";
}
std::cout << "\n";
}
Loops?
I want to loop from 33 - 47 and - 58 to 64 and 91 to 96 from ASCII
table and then display all together
Just do one thing after the other
for (char c=33; c<48; c++) { std::cout << c; }
for (char c=58; c<65; c++) { std::cout << c; }
for (char c=91; c<97; c++) { std::cout << c; }
No Loops
once the loop is done it should displayed like this
!"#$%&'()*+,-./:;<=>?@[]^_`{|}~
It is not really clear why you want to loop in the first place. If you want to print that characters you can print them via
std::cout << "!\"#$%&'()*+,-./:;<=>?@[]^_`{|}~\n";
just note that you have to espace the "
(ie put a \
in front).
Loops
If you do write loops, try to avoid magic numbers. Instead give your numbers meaningful names as in start
/stop
or height
/width
vs 33
/48
. When you can, use iterators instead of indexes. Range-based for loops even allow you to ignore the iterators, as in
std::string outp = "!\"#$%&'()*+,-./:;<=>?@[]^_`{|}~";
for (auto letter : outp) std::cout << letter;