Display in C++ 1) What is the displayed value of sum1? int i, ntemps = 4; // tot
ID: 3916360 • Letter: D
Question
Display in C++
1) What is the displayed value of sum1?
int i, ntemps = 4; // total number of temp values = 4
int temp; // temperature value
int count1 = 0, count2 = 0, count3 = 0, count4 = 0;
int sum1 = 0, sum2 = 0, sum3 = 0;
for ( i = 0; i < ntemps; i++)
{
cout << “Enter temperature value”
cin >> temp;
if (temp > 50) count1++;
if (temp > 40 && temp <= 60) count2++;
if (temp > 40 || temp <= 50) count3++;
sum1 = temp;
sum2 = sum2 + temp;
sum3 = temp + 10;
}
cout << count1 << count2 << count3 << sum1 << sum 2<< sum3 << i;
Assume the user has entered the following 4 temperature values: 50, 60, 70, 80
2) What is the displayed value of count1?
int i, ntemps = 4; // total number of temp values = 4
int temp; // temperature value
int count1 = 0, count2 = 0, count3 = 0, count4 = 0;
int sum1 = 0, sum2 = 0, sum3 = 0;
for ( i = 0; i < ntemps; i++)
{
cout << “Enter temperature value”
cin >> temp;
if (temp > 50) count1++;
if (temp > 40 && temp <= 60) count2++;
if (temp > 40 || temp <= 50) count3++;
sum1 = temp;
sum2 = sum2 + temp;
sum3 = temp + 10;
}
cout << count1 << count2 << count3 << sum1 << sum 2<< sum3 << i;
Assume the user has entered the following 4 temperature values: 50, 60, 70, 80
Explanation / Answer
execute the following program like this:-
1). for loop:-
i = 0
entered temp value = 50, so temp = 50
2nd and 3rd if body is executed based on its condition so,count2 = 0 + 1 = 1, count3 = 0 +1 = 1
sum1 = temp = 50
sum2 = sum2 + temp = 0+50 = 50
sum3 = temp + 10 = 50 + 10 = 60
// end of first iteration
i = 1 // start of 2nd iteration
here,entered temp value = temp = 60
based on the if conditions,1st and 2nd if body is executed so count1 = 0 + 1 = 1 , count2 = 1 + 1 = 2
sum1 = temp = 60
sum2 = sum2 + temp = 50 + 60 = 110
sum3 = temp + 10 = 60 + 10 = 70
// ending of 2nd iteration
i = 2 // start of 3rd iteration
entered temp value = temp = 70
based on the temp value,only 1st if body is executed so, count1 = 1 + 1 = 2
sum1 = temp = 70
sum2 = sum2 + temp = 110 + 70 = 180
sum3 = temp + 10 = 70 + 10 = 80
// end of 3rd iteration
i = 3 // start of 4th iteration
entered temp value = temp = 80
based on the temp value,only 1st if body is executed so,count1 = 2 + 1 = 3
sum1 = temp = 80
sum2 = sum2 + temp = 180 + 80 = 260
sum3 = temp + 10 = 80 + 10 = 90
// end of 3rd iteration
i = 4// for loop terminates
"cout << count1 << count2 << count3 << sum1 << sum 2<< sum3 << i;" statement prints
3 2 1 80 260 90 4
after the termination of the code we can simply see that the output is clearly
count1 = 3
count2 = 2
count3 = 1
sum1 = 80
sum2 = 260
sum3 = 90
so,sum2 = 260
2).clearly ,from above count1 = 3