+ 3
For loop request.
I want to output: A B C D E F G H I J any help is appreciated..
6 Réponses
+ 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;
}
+ 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++;
+ 3
thanx got it
+ 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?
+ 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
+ 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