0

can anyone explain me this full code...to print this pattern

#include <iostream> using namespace std; int main() { int b; int length=5; int j; for (int i=0;i<=length;++i) //here length = 5 { int b=9; for (j=0;j<length-i;j++) //for blank spaces cout<<" "; for(j=0;j<2*i+1;j++) { if(j<(2*i+1)/2) cout<<b--; else cout<<b++; } cout<<"\n"; } return 0; }

8th Feb 2017, 4:50 PM
Tushar
1 Answer
0
There is a few places where things could be improved. This code basically prints numbers in a few nested for loops. commented code for you: \\includes for input and output streams #include <iostream> \\using standard namespace using namespace std; \\main entry point int main() { \\declare 3 variables, assign 5 to length int b; int length=5; int j; \\ make a for loop starting at 0 \\ loop until it is less than or equal to length \\ length is 5 so it will run 0,1,2,3,4,5 (6 times) \\ it will increase by 1 each time until then for (int i=0;i<=length;++i) { \\this code here will run 6 times as explained \\it sets b to 9 every time int b=9; \\another for loop notice there is no braces so \\it only executes next line for (j=0;j<length-i;j++) \\that line just prints spaces (6 of them) cout<<" "; \\another for loop from 0 to (2 times i) \\ i is the variable that is being looped from earlier \\ so j loops from 0 to (0, 2, 4, 6, 8,10) for(j=0;j<2*i+1;j++) { \\if j <= i (this could be written much better) \\ then print b then take 1 from it (starts as 9) if(j<(2*i+1)/2) cout<<b--; \\otherwise print b then add 1 to it else cout<<b++; } \\finally start a new line cout<<"\n"; } \\exit the main entry point and return 0 return 0; }
10th Feb 2017, 2:33 PM
Aaron Edmistone
Aaron Edmistone - avatar