Trying to fulfill the coding prompt
Input a list of positive numbers, find the mean (average) of the numbers, and output the result. Use a subprogram to input the numbers, a function to find the mean, and a subprogram to output the result.
I have done smaller calls with passing arguments but this one requires 3 separate subprograms, 1 for input, 1 for calculations and one to display the result.
So far my program is does not start the initial call for input
#include <iostream>
using namespace std;
//prototypes
int prompt(int sum, int count );
float average(int sum, int count);
void result(float avg);
int main()
{
int num;
cout << "Welcome to Keith's Averaging program";
cout << endl;
int prompt();
int average (int sum, int count);
void result (float avg);
return 0;
}
//Prototype Definitions
//get numbers from users
int prompt()
{
int num, sum, count;
cout << "Enter numbers and I will Average them." << endl;
cout << "Please enter a number: ";
cin >> num;
sum = sum + num;
if(num == 0)
{
cout << "Guess you don't want an average";
cout << endl;
cout << "Goodbye";
}
for(count=0; num !=0; count++)
{
cout << "Please enter a positive number, enter zero to compute the avg: ";
cin >> num;
if(num < 0)
{
cout << "Enter a positive number:";
cin >> num;
}
sum = sum + num;
}
Displays my welcome message then exits
I have put some comments in your code as explanation.
#include <iostream>
using namespace std;
//prototypes // These are declarations, definitions should also contain
// same function signatures
int prompt(int& sum, int& count); // accept arguments as reference (Read about it)
float average(int& sum, int& count);
void result(float& avg);
int main()
{
// int num; // don't need num in this function, not used
int sum = 0, count = 0; // create variables sum and count and initialize them to 0
float avg;
cout << "Welcome to Keith's Averaging program";
cout << endl;
prompt(sum, count); // don't need function return type and argument return type when calling
// a function
cout << sum << " " << count << endl; // print the values after prompt() call
// prompt() call must have filled the values sum and count
average(sum, count);
result(avg);
return 0;
}
//Prototype Definitions
//get numbers from users
int prompt(int& sum, int& count)
{
int num;
cout << "Enter numbers and I will Average them." << endl;
cout << "Please enter a number: ";
cin >> num;
sum = sum + num;
if(num == 0)
{
cout << "Guess you don't want an average";
cout << endl;
cout << "Goodbye";
}
for(count=0; num !=0; count++)
{
cout << "Please enter a positive number, enter zero to compute the avg: ";
cin >> num;
if(num < 0)
{
cout << "Enter a positive number:";
cin >> num;
}
sum = sum + num;
}
}
float average(int& sum, int& count){
// TODO: implement this
}
void result(float& avg) {
// TODO: implement this
}
I have changed various parts of your code. I changed the function prototypes so that they take arguments by reference.
In the int main() function, I created two variables sum and count and initialized them to 0 - we will use these variables when calling those functions.
In the int prompt() function, I changed the function signature so that it matches the declared definition (otherwise it would have been some other function). Also, I removed the local declarations sum and count since we now have them as function arguments.
I have also put the definition blocks for other two functions and you can implement them (I have marked them as // TODO).
Related
I know most of people may find this too easy but i am still very new to programming so i need a program that allows the user to enter 100 numbers and the program finds their sum , i have tried this:
#include <iostream>
using namespace std;
int main ()
{
float x;
int counter=0 , sum=0;
cout<<"enter a number\n";
cin>>x;
do {
sum+=x;
cout<<"sum="<<sum<<endl;
counter++;
}
while ( counter<=100 );
}
i found this making 'x' has the value that i entered first time but i need to enter different value every time it repeats (entering 100 different values) what should i add?
Simply move the input prompt and cin into the loop
do
{
cout << "enter a number\n";
cin >> x
sum += x;
cout << "sum=" << sum << endl;
counter++;
}
while (counter < 100);
Take note that it should be counter < 100 instead of counter <= 100 if you want it to be exactly 100 times.
You just have put the cin into the loop so that in every iteration it asks for an input.
Also note that the variable sum is an integer, while the variable x is a float.
So you probably should make sum a float or make x an integer to avoid getting unexpected results .
#include <iostream>
using namespace std;
int main () {
float x,sum=0;
int counter=0 ;
do {
cout<<"enter a number\n";
cin>>x;
sum+=x;
cout<<"sum="<<sum<<endl;
counter++;
} while ( counter<=100 );
}
You can use a For loop also for simplicity. Make sure to use long int data type for storing sum because the sum of 100 integers may lead to integer overflow.
#include <iostream>
using namespace std;
int main() {
int x, num;
long int sum=0;
cout<<"Enter the number you want to find the sum:";
cin>>num; // Like 100
for(int counter=1;counter<=num;counter++)
{
cout<<"Enter a number:";
cin>>x;
sum+=x;
}
cout<<"Sum of "<<num<<" numbers is:"<<sum;
return 0;
}
You could also do it in a for loop:
float input, sum;
for(int i = 0;i < 100; i++){
cout << "Enter a number << endl;
cin >> input;
sum += input;
cout << "sum is: << sum << endl;
}
Look out at the condition of your while. You are saying this -> counter<=100, and counter is initialized to 0. So, you will enter from 0 to 100(included) = 101 times. If you only want to enter 100 times, the condition should be
do
{
cout << "enter a number\n";
cin >> x
sum += x;
cout << "sum=" << sum << endl;
counter++;
}
while (counter < 100);
or initialize counter to 1, and then you can use the same while as you had.
while (counter < total)
{
inFile >> grade;
sum += grade;
counter++;
}
Above is the while loop I had for my original program and below is my attempt at converting that to a for loop.
for (counter = 0; counter < total; counter++)
{
inFile >> grade;
cout << "The value read is " << grade << endl;
total = total + grade;
}
This is a simple program to get grade averages. Here is the entire program:
#include <iostream>
#include <fstream>
using namespace std;
int average (int a, int b);
int main()
{
// Declare variable inFile
ifstream inFile;
// Declare variables
int grade, counter, total;
// Declare and initialize sum
int sum = 0;
// Open file
inFile.open("input9.txt");
// Check if the file was opened
if (!inFile)
{
cout << "Input file not found" << endl;
return 1;
}
// Prompt the user to enter the number of grades to process.
cout << "Please enter the number of grades to process: " << endl << endl;
cin >> total;
// Check if the value entered is outside the range (1…100).
if (total < 1 || total > 100)
{
cout << "This number is out of range!" << endl;
return 1;
}
// Set counter to 0.
counter = 0;
// While (counter is less than total)
// Get the value from the file and store it in grade.
// Accumulate its value in sum.
// Increment the counter.
while (counter < total)
{
inFile >> grade;
sum += grade;
counter++;
}
// Print message followed by the value returned by the function average (sum,total).
cout << "The average is: " << average(sum,total) << endl << endl;
inFile.close();
return 0;
}
int average(int a, int b)
{
return static_cast <int> (a) /(static_cast <int> (b));
}
I tried to convert while loop to a for loop but when I debug I get an infinite loop. There are no errors when I build my solution. I'm not sure what other details to add.
You are increasing the value of total in the for loop. Hence, counter never reached total if you keep entering positive values.
Perhaps you meant to use sum instead of total in the loop.
for (counter = 0; counter < total; counter++)
{
inFile >> grade;
cout << "The value read is " << grade << endl;
sum = sum + grade;
}
You are using wrong variables names, value of total is increasing in the for loop so it becomes an infinite loop, use a different variable names for storing sum and for for-loop termination condition.
I've been trying to write a C++ program that calculates your end of year grade (an exercise given by the Google for Education C++ course). The program works, except for the fact that it doesn't calculate your final grade, instead, it just outputs "0". I have searched the code and can't seem to find the problem.
#include <iostream>
using namespace std;
int check(int a) {
if (!(cin >> a)) {
cout << "Come on, that isn't a score" << endl;
return 0;
}
}
int assignments() {
int assignment1 = 0;
int assignment2 = 0;
int assignment3 = 0;
int assignment4 = 0;
cout << "Enter the score for the first assignment. ";
check(assignment1);
cout << "Enter the score for the second assignment. ";
check(assignment2);
cout << "Enter the score for the third assignment. ";
check(assignment3);
cout << "Enter the score for the fourth assignment. ";
check(assignment4);
return ((assignment1 + assignment2 + assignment3 + assignment4) / 4 * 0.4);
}
int mid() {
int midterm = 0;
cout << "Enter the score for the midterm. ";
check(midterm);
return (midterm * 0.15);
}
int finalex() {
int finals = 0;
cout << "Enter the score for the final. ";
check(finals);
return (finals * 0.35);
}
int participation() {
int parti = 0;
cout << "Enter the class participation grade. ";
check(parti);
return (parti * 0.1);
}
int main() {
int assign = assignments();
int midt = mid();
int fingra = finalex();
int partigra = participation();
cout << "The final grade is: " << assign + midt + fingra + partigra << endl;
}
(The reason I have a different program for every grade type is because the course states that you should make as many functions as possible)
Either you should pass value to check() as reference or make check to return input value.
Change
int check(int a)
to
int check(int& a)
Second method
Modify check to
int check(int a) {
if (!(cin >> a)) {
cout << "Come on, that isn't a score" << endl;
return a;
}
}
And use return value to assign input to variables. Like
int midterm = 0;
cout << "Enter the score for the midterm. ";
midterm=check(midterm);
Your cin >> a statements updates value of a local variable which is gone as soon as check() returns. You want to update value of variables that are actually used for calculating grades. Just change the function check() to pass by reference check(int &a) or pass a pointer check(int *a)
In a problem i am working on i have a function that checks if the number of spherical and cylindrical holes in rectangular block are greater than zero. In this problem i have to call the function twice. My problem is that the first time i call the function 'HoleCheck' is is running twice and assuming that zero is entered in for the cylindrical holes and makes me re-enter the value for spherical holes. How can i make it to only run once for the spherical hole check?
#include <iostream>
#include <string>
using namespace std;
void Check(double arr1[], string arr2[]);
void HoleCheck(int arr3[], string arr4[]);
int main()
{
double DimArray[3];
string MyArray[3] = { "Height", "Length", "Width"};
int totalholes[2];
string holes[2] = { "Spherical", "cylindrical"};
cout << "Enter the height, length and width of rectangle in centimeters: ";
cin >> DimArray[0] >> DimArray[1] >> DimArray[2];
Check(DimArray, MyArray);
cout << "How many spherical bubbles are present? ";
cin >> totalholes[0];
HoleCheck(totalholes, holes);
cout << "How many cylindrical holes are present? ";
cin >> totalholes[1];
HoleCheck(totalholes, holes);
return 0;
}
void Check(double arr1[], string arr2[])
{
int i;
for (i = 0; i < 3; i++)
{
while (arr1[i] <= 0)
{
cout << "Your entered " << arr2[i] << " is less than zero!\n";
cout << "Please re-enter a valid number --> ";
cin >> arr1[i];
}
}
}
void Check(double arr1[], string arr2[])
{
int z;
for (z = 0; z < 2; z++)
{
while (arr3[z] <= 0)
{
cout << "The number of " << arr4[z] << " holes must be greater than 0.\n";
cout << "Please re-enter a valid number --> ";
cin >> arr3[z];
}
}
}
Assuming that your second Check function is actually HoleCheck and that was a typo:
Your HoleCheck Function checks both elements of its arr3, but you are calling it before you enter any values into totalHoles[1].
Either just remove the first call to HoleCheck or change it so you can tell it which entry in the array to check.
This code simply takes a number, adds this to another number and then prints the result out. It also says whether the number is high or low. This is all done in a bool function:
#include <iostream>
using namespace std;
bool addition(int num, int num2, int total);
int main()
{
int num, num2,total;
cout << "enter a number"<< endl;
cin >> num;
cout<< "enter another number" << endl;
cin >> num2;
addition(num, num2, total);
{
cout <<"the first number is:" << num<< " the second number is: "<< num2 << endl;
cout << "the total is: " << total << endl;
if (1) {
cout << "its low" ;
} else {
cout << "its high";
}
cout << endl;
}
}
bool addition (int num, int num2, int total) {
//total = 0;
total = num + num2;
if (total >= 10){
return 1;
} else {
return -1;
}
}
The problem is this program is ALWAYS saying the number is low and the total is ALWAYS 32767. I don't know why.
You're passing total by value, which means addition() can't modify main's total variable. Pass by reference instead:
bool addition (int num, int num2, int &total)
The reason you always get "its low" is because if (1) is always true. Probably you want something like:
bool result = addition(num, num2, total);
Followed later by:
if (result)
You are passing total by its value. Use pointer or reference instead to modify its value inside the addition function.
Besides, returning 1 or -1 from a function with a boolean return type has same effect, as in C++ any nonzero value evaluates to true. Return either true or false (or either some nonzero value or 0).
Try passing total by reference instead of value like this:
bool addition (int num, int num2, int &total)
instead of
bool addition(int num, int num2, int total);
Also your condition if (1) is always true. So you will always get low
#include <iostream>
using namespace std;
bool addition (int num, int num2, int &total) {
total = num + num2;
return total >= 10;
}
int main()
{
int num, num2,total;
cout << "enter a number"<< endl;
cin >> num;
cout<< "enter another number" << endl;
cin >> num2;
bool additionResult = addition(num, num2, total);
{
cout <<"the first number is:" << num<< " the second number is: "<< num2 << endl;
cout << "the total is: " << total << endl;
if (!additionResult){
cout << "its low" ;
}
else{
cout << "its high";
}
cout << endl;
}
}