Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

For each sample of code given below, indicate precisely how many times each line

ID: 3859024 • Letter: F

Question

For each sample of code given below, indicate precisely how many times each line runs in terms of the variables given. Sometimes, you will be able to give an exact integral answer, like "10". Other times, your answer will be in terms of n or some other variable or combination of variables. If the snippet of code is a method, you do not have to write the number of times the top line (the method declaration itself) is executed.

Q1.

double sum_triples(double array[], int n) {//n: size of the array. Assume n is divisible by 3

double sum=0;

for (int i=0; i<n; i=i+3)

sum = sum + array[ i ];

return sum;

}

Q2.

double sum_exponentials(int n){ //n is a power of 3, i.e., n=3^k or k=log n base 3

int sum=0;

for (int i=1; i<n; i=i*3)

sum = sum + i;

return sum;

}

Q3.

for (int i=0; i<n; i++) {

for (int j=n; j>=i; j--)

cout << i << “,” << j <<endl;

}

Q4.

for (int i=0; i<n; i++) { //assume n is divisible by 2 => n = 2*k

for (j=n/2; j>i; j--)

sum = i+j;

}

Explanation / Answer

Q1

Here the length of the n is 3 so first time it will check 0<3 next it will add 3 to i it become 3<3 so the condition fails.


#include <iostream>
#include <string>
using namespace std;
double sum_triples(double array[], int n) {//n: size of the array. Assume n is divisible by 3
double sum=0;
int noofTimes=0;
  
for (int i=0; i<n; i=i+3)
{
  
sum = sum + array[ i ];

noofTimes++;
}
cout<<"The no of times loop executed "<<noofTimes;

return sum;
}
int main()
{
double arr[3]={1,2,3};
  
sum_triples(arr,3);
  
}

Output:

The no of times loop executed 1

Q2:


#include <iostream>
#include <string>
using namespace std;
double sum_exponentials(int n){ //n is a power of 3, i.e., n=3^k or k=log n base 3
int sum=0;
int noofTimes=0;
for (int i=1; i<n; i=i*3)
{
  
sum = sum + i;
noofTimes++;
}
cout<<"The no of times loop executed "<<noofTimes;
return sum;

}

int main()
{
sum_exponentials(6);
  
}

Output:

The no of times loop executed 2

Q3:


#include <iostream>
#include <string>
using namespace std;


int main()
{
int noofTimes=0,n=3;
for (int i=0; i<n; i++) {
for (int j=n; j>=i; j--)
cout << i <<"," << j <<endl;
noofTimes++;
}
cout<<"The no of times loop executed "<<noofTimes;
}

Output:

0,3

0,2

0,1

0,0

1,3

1,2

1,1

2,3

2,2

The no of times loop executed 3

Q4:


#include <iostream>
#include <string>
using namespace std;


int main()
{
int noofTimes=0,n=4,sum=0;
for (int i=0; i<n; i++) { //assume n is divisible by 2 => n = 2*k
for (int j=n/2; j>i; j--)
sum = i+j;
noofTimes++;
}


cout<<"The no of times loop executed "<<noofTimes;
}

Output:

The no of times loop executed 4