+ 3

For loop request.

I want to output: A B C D E F G H I J any help is appreciated..

22nd Mar 2017, 3:20 PM
Sayantan Ghosh
Sayantan Ghosh - avatar
6 Answers
+ 15
int x = 65; for (int i = 1; i < 5; i++) { for (int j = 0; j < i; j++) { cout << static_cast<char>(x); x++; } cout << endl; }
22nd Mar 2017, 3:32 PM
Hatsy Rei
Hatsy Rei - avatar
+ 10
@Sayantan ghosh wrote: << Can u explain why? >> Because you increment your 'ch' variable before first print... You can fix your code by swapping the 2 lines of the inner 'for' loop: cout<<" "<<ch; ch++;
22nd Mar 2017, 5:13 PM
visph
visph - avatar
+ 3
thanx got it
22nd Mar 2017, 3:41 PM
Sayantan Ghosh
Sayantan Ghosh - avatar
+ 2
I tried this way.. #include <iostream> using namespace std; int main() { char ch='A'; for(int i=1;i<=4;i++) {for(int j=0;j<i;j++) { ch++; cout<<" "<<ch; } cout<<" "<<endl; } return 0; } But the out put is: B C D E F G H I J K Can u explain why?
22nd Mar 2017, 3:37 PM
Sayantan Ghosh
Sayantan Ghosh - avatar
+ 2
yeah. in your j for loop, try placing the ch++ below the cout. it is incrementing before the first print. hence you get B
22nd Mar 2017, 3:39 PM
Puspal Ghosh
Puspal Ghosh - avatar
+ 1
//ASCII value of A is 65. so, solving by typecasting , x = 65; for(j=0;j<4;j++) { for(i=0;i<j+1;i++) printf("%c ",(char)x++); printf("\n"); } //you could also define a character array with those values and run it on a loop
22nd Mar 2017, 3:35 PM
Puspal Ghosh
Puspal Ghosh - avatar