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

Write a C++ program using the while loop to find the sum and the average of all

ID: 3813668 • Letter: W

Question

Write a C++ program using the while loop to find the sum and the average of all the odd integers 1, 3, 5, 7, ..., 499. Display the sum and the average. Write a C++ program that reads from the keyboard up to 10 numbers, using a while loop with a SENTINEL, to count and add the positive values and then display the results. Your program should terminate whenever it either reads 10 number or a negative number. You assume at least there is one number. Here is an example of input/output: 2 7-6 Number of positive numbers is: 2 The sum of the positive numbers is: 9 Here is another example of input/output: 2 7 6 10 3 9 5 9 4 2 -10 Number of positive numbers is: 10 The sum of the positive numbers is: 57 Homework: The factorial of a nonnegative n written as n! is defined as follows: n! = n*(n - 1)*(n - 2)*... *1 (for all values of n greater than 0) and 0! = 1. For example 5! = 5*4*3*2*1 which is 120. Write a C++ program that reads a nonnegative integer and computes and prints its factorial.

Explanation / Answer

Hey,

Following are the answers with explanation to the problems.

Please give a thumbs up, if my answer helped you. :)

Exercise 1 -

#include <bits/stdc++.h>

using namespace std;

int main() {

   int x = 1; //First number

   int sum = 0;
   int cnt = 0;
   while(x <= 499) { //while number is less than 499
       cnt++; //Increment the counter
       sum += x; //Add current number to sum

       x += 2; //get next odd number
   }

   cout << sum << " " << (sum / (1.0 * cnt)) << endl; //print sum and average as avg = sum / count
   return 0;
}

Exercise 2 -

#include <bits/stdc++.h>

using namespace std;

int main() {

   int x;

   int sum = 0; //Initialize sum as 0
  
   cin >> x; //Take first input

   int cnt = 1;
  
   while(x >= 0 && cnt <= 10) { //while input number is greter than 0 and elements encountered so far are less than 10
       sum += x; //add current number to sum
       cin >> x; // get next number
       cnt++; //increment counter
   }


   cout << "Sum is - " << sum << endl;
   return 0;
}

For the homework Question, You need to calculate the factorial of the number.

In order to do so, we will first take the number as input, then we will iterate from 1 to n and multiply each value in our answer. The answer is initialized to 1.

#include <bits/stdc++.h>

using namespace std;

int main() {

   int n;

   cin >> n;

   long long int ans = 1;

   int i = 1;
  
   while(i <= n) {
       ans = ans * i;
       i++;
   }

   cout << ans << endl;
   return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote