In: Computer Science
Please, explain your answer clearly (step-by-step), so I can trace the output without using the Visual Studio Program.
Please, clearly describe how the mechanism of the loop works.
The answers in bold.
for (int i = 0; i < 5; i++)
{
for (int j = 0; j <= i; j++)
{
cout << i << " ";
}
}
{
int result = 0;
for (int i = 0; i < size; i++)
{
result = result + A[i];
}
return result;
}
int main()
{
int myarr[10] = { 2, 4, 10, 1, 2, 4, 8, 1, 2, 1 };
for (int i = 0; i < 3; i++)
{
cout << my_fun(myarr, myarr[i]);
}
}
Code Snippet 1:
OUTPUT:
0 1 1 2 2 2 3 3 3 3 4 4 4 4 4
Explanation:
The line by line description of the source code is given below:
//outer for loop
//this loop will be executed five time for i= 0, 1, 2, 3,
4
for (int i = 0; i < 5; i++)
{
//inner for loop
//the repetition of this loop depend upon the outer for loop
//for i = 0, this loop will execute for one time and print 0 with
space
//for i = 1, this loop will execute for two times and print 1 with
space
//for i = 2, this loop will execute for three times and print 2
with space
//for i = 3, this loop will execute for four times and print 3 with
space
//for i = 4, this loop will execute for five times and print 4 with
space
for (int j = 0; j <= i; j++)
{
//print the value of variable 'i' and print the space at
the last
cout << i << " ";
//end inner for loop
}
//end outer for loop
}
Code Snippet 2:
OUTPUT:
61735
Explanation:
The line by line description of the source code is given below:
//function to calculate the sum of an array of a given
size
int my_fun(int A[], int size)
{
//variable declaration and initialization
int result = 0;
//the repetiotion of the for loop will depend upon the
size
for (int i = 0; i < size; i++)
{
//the variable result will be increment array element value
of index i
result = result + A[i];
}
//return the sum of array
return result;
}
int main()
{
//array declaration and initialization
int myarr[10] = { 2, 4, 10, 1, 2, 4, 8, 1, 2, 1 };
//this for loop will execute three times for i = 0, 1, and
2
for (int i = 0; i < 3; i++)
{
//This statement will display the return value of the
called function
//the first argument is the address of the array
//the second argument is the size of the array
//For the first iteration, the second argument will pass the value
of array first element
//The array first element is 2, so it will pass 2 as a second
argument
//the called function returns the sum of the first two
elements
//For the second iteration, the second argument will pass the value
of array second element
//The array second element is 4, so it will pass 4 as a second
argument
//the called function returns the sum of the first four
elements
//For the third iteration, the second argument will pass the value
of array third element
//The array third element is 10, so it will pass 10 as a second
argument
//the called function returns the sum of first 10
elements
cout << my_fun(myarr, myarr[i])<<" ";
}
}