In: Computer Science
What is the ouput of the following code?
void loop(int num)
{
for(int i = 1; i < num; ++i)
{
for(int j = 0; j < 5; ++j)
{
cout << j;
}
}
}
int main()
{
loop(3);
return 0;
}
Starting from main, the function
loop(3)
is called.
So, the flow of the program moves to the function loop.
In the function loop there are two for loops:
1. for(int i = 1; i < num; ++i) (outer loop)
2. for(int j = 0; j < 5; ++j) (inner loop)
The outer loop will run for 2 times, for the value of i=1,2 and then the condition fails thus coming out of the loop.
The inner loop will run for 5 times, for the value of j=0,1,2,3,4 and then the condition fails.
Therefore, the execution is as follows:
outer loop iteration 1: value of i=1
inner loop iteration 1: value of j=0
output: 0
inner loop iteration 2: value of j=1
output: 01
inner loop iteration 3: value of j=2
output: 012
inner loop iteration 4: value of j=3
output: 0123
inner loop iteration 5: value of j=4
output: 01234
outer loop iteration 2: value of i=1
inner loop iteration 1: value of j=0
output: 012340
inner loop iteration 2: value of j=1
output: 0123401
inner loop iteration 3: value of j=2
output: 01234012
inner loop iteration 4: value of j=3
output: 012340123
inner loop iteration 5: value of j=4
output: 0123401234
Therefore, the output of the given code is 0123401234.