0

How this program executes this result!?

#include "stdafx.h" #include "iostream" using namespace std; void main() { int x = 0; int j; for ( x=1; x<=5 ; x++){ for (j =1; j<=x; j++) cout << x << endl; } } Results :- 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5.

23rd Jan 2018, 8:36 AM
Cimraan Abdullah
Cimraan Abdullah - avatar
3 Antworten
+ 6
There's nothing mind-blowing about it, especially when it uses void return type for main. http://www.stroustrup.com/bs_faq2.html#void-main Now, back on topic. The outer loop runs for values from 1 to 5. These values are represented by x, within the loop. It uses a nested loop to loop for x amount of times, each printing the value of x. Hence, if the value of x is 3, then 3 will be printed for 3 times. If the value of x is 4, then 4 will be printed 4 times. Similarly, if the value of x is n, then n will be printed for n times.
23rd Jan 2018, 8:41 AM
Hatsy Rei
Hatsy Rei - avatar
+ 2
@cimraan #include "stdafx.h" #include "iostream" using namespace std; void main() { int x = 0; int j; for ( x=1; x<=5 ; x++){. //line 8 for (j =1; j<=x; j++). //line 9 cout << x << endl; } } Results :- 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 there are 2 loops(lets call ,1st for line 8,2nd for line 9) the1st one takes the value from 1 to 5 and 2nd takes the value from 1 to value of x from 1st loop hence when x passes as 1 in 1st loop 2nd loop takes x value from 1 to 1 output 1 when x passes as 2 in 1st loop 2nd loop takes x value from 1 to 2 means 1,2 (printing 2 times the x value) output 1 2 2 when x passes as 3 in 1st loop 2nd loop takes x value from 1 to 3 means 123 printing 3 times the x value output 1 2 2 3 3 3 similarly for 4 and 5 ....................
23rd Jan 2018, 2:28 PM
Hack Erer
Hack Erer - avatar
0
still didn't get it😥 but thanks a lot @Rei
23rd Jan 2018, 8:51 AM
Cimraan Abdullah
Cimraan Abdullah - avatar