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.
Related
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).
I am currently stuck in my homework and the problem is that I need to create a program that will ask for 5 integer numbers from which I should determine the highest and lowest value. I am quite confused as of now, and my initial code is this:
#include<iostream>
using namespace std;
int main(){
int num1,num2,num3,num4,num5,min=0,max=0;
cout << " Enter 1st number : ";
cin >> num1;
cout << " Enter 2nd number : ";
cin >> num2;
cout << " Enter 3rd number : ";
cin >> num3;
cout << " Enter 4th number : ";
cin >> num4;
cout << " Enter 5th number : ";
cin >> num5;
do{
if(num1<num2 && num1<num3 && num1<num4 && num1<num5 ){
max = num1;}
if(num2<num1 && num2<num3 && num2<num4 && num2<num5 ){
max = num2;}
if(num3<num1 && num3<num2 && num3<num4 && num3<num5 ){
max = num3;}
if(num4<num1 && num4<num3 && num4<num2 && num4<num5 ){
max = num4;}
if(num5<num1 && num5<num3 && num5<num4 && num5<num2 ){
max = num2;}
}while(max>0);
cout << " The highest number is : " <<max;
return 0;
}
Any help would be appreciated. Thanks in advance!
You should store your numbers into a std::vector<int> or std::array and then use the std::minmax_element algorithm to obtain the largest and smallest number.
If you are allowed to use std::max and std::min, you can use:
max = std::max({num1, num2, num3, num4, num5});
min = std::min({num1, num2, num3, num4, num5});
to simplify the code in the loop.
This would be my solution without using arrays.
I'd suggest you to try it yourself before. You don't learn when you just copy code.
#include <iostream>
int main() {
int i=0, num, min=INT_MAX, max=INT_MIN;
do {
std::cout << "Enter number: ";
std::cin >> num;
if (num < min) {
min = num;
}
if (num > max) {
max = num;
}
i++;
} while (i < 5);
std::cout << "The max number is: " << max << std::endl;
std::cout << "The min number is: " << min << std::endl;
return 0;
}
If you don't need to remember, you can loop for e.g. 5 times, then have a comparison before asking the next number.
so generally (idea, write it yourself and learn):
for (5 times)
ask user input, save as input
if largest number is null, then equal to input
else if largest number is smaller, then set input equal to largest number
Continue for loop times.
Rather than compare all the numbers each time. Simply compare your current smallest against the numbers in sequence.
int data[5];
// read numbers into data.
int min = data[0]; // Guess that number 0 is the smallst number.
// Now check if the guess is correct and update if you are wrong.
for(int loop = 0; loop < 5; ++loop)
{
// check if data[loop] is smaller than your current guess.
// if it is smaller than update your guess.
// when you have checked all the values exit the loop.
}
std::cout << "Smallest: " << min << "\n";
There is no need to use a loop to do this you can do that without it else if it's necessary to use a loop you must use an array or some other data structure
This is my first post on here so please don't kill me for my noobishness.
I recently made a program for fun to put in a ton of numbers and have it put out the mean, not very useful but I thought I would see if I could. I would love it if someone could explain to me how I could improve my code using arrays instead of lots of variables, but still achieve the same thing, maybe even more efficiently.
My code looks like this:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main() {
int q1;
int q2;
int q3;
int q4;
int q5;
int q6;
int q7;
int q8;
int q9;
int q10;
int q11;
int q12;
int f;
//Used for the total of all values
int t;
//Used for the total to be divided
int a;
//Used for dividing the numbers.
cout << "We will be finding a mean. Enter the amount of numbers that will be entered, the maximum is 12: ";
cin >> a;
cout << "Now enter what numbers you want to find the mean for, because the maximum is 12, if you have less than 12, enter 0 for the rest: ";
cin >> q1;
cin >> q2;
cin >> q3;
cin >> q4;
cin >> q5;
cin >> q6;
cin >> q7;
cin >> q8;
cin >> q9;
cin >> q10;
cin >> q11;
cin >> q12;
f = q1 + q2 + q3 + q4 + q5 + q6 + q7 + q8 + q9 + q10 + q11 + q12;
cout << f / a << '\n';
system("pause");
}
Any advice is very appreciated! This was made in Visual Studio just in case you needed to know.
Of course arrays can make your life easier!
Here's how you could have accomplished the same task as above, with arrays:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main() {
int totalNums;
cout << "We will be finding a mean.\n";
cout << "You can only enter up to 12 numbers;
// Declare an array to hold 12 int's
int nums[12];
// i will count how many numbers have been entered
// sum will hold the total of all numbers
int i, sum = 0;
for(i = 0; i < 12; i++) {
cout << "Enter the next number: ";
cin >> nums[i];
sum += nums[i];
}
cout << "The mean is: " << (sum / totalNums) << '\n';
//Try to avoid using system!
system("pause");
}
But, why use an array?
There's no need to keep any of the numbers after you add them to the total, so why use an array?
You can accomplish the same task without an array and with only one variable for the numbers!
#include "stdafx.h"
#include <iostream>
using namespace std;
int main() {
int totalNums;
cout << "We will be finding a mean.\n";
cout << "Enter the amount of numbers that will be entered: ";
cin >> totalNums;
// i will count how many numbers have been entered
// sum will hold the total of all numbers
// currentNum will hold the last number entered
int i, sum = 0, currentNum = 0;
for(i = 0; i < totalNums; i++) {
cout << "Enter the next number: ";
cin >> currentNum;
sum += currentNum;
}
cout << "The mean is: " << 1.0 * sum / totalNums << '\n';
//Try to avoid using system!
system("pause");
}
Arrays can be considered as series of variables each of which has ids.
integers between 0 and (number of elements) - 1 (both inclusive) are available ids.
Using that with loop, your code can be like this (sorry, I hate stdafx.h):
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
int q[12];
int f;
//Used for the total of all values
int t;
//Used for the total to be divided
int a;
//Used for dividing the numbers.
cout << "We will be finding a mean. Enter the amount of numbers that will be entered, the maximum is 12: ";
cin >> a;
cout << "Now enter what numbers you want to find the mean for, because the maximum is 12, if you have less than 12, enter 0 for the rest: ";
for (int i = 0; i < 12; i++) {
cin >> q[i];
}
f = 0;
for (int i = 0; i < 12; i++) {
f += q[i];
}
cout << f / a << '\n';
system("pause");
}
You may use the numbers read in the future, but currently the numbers aren't used except for calculating the sum, so you can omit the array and do addition while reading. Also I deleted the variable t, which is unused and stopped using using namespace std;, which is not considered as good.
#include <cstdlib>
#include <iostream>
using std::cin;
using std::cout;
int main() {
int q;
int f;
//Used for the total of all values
int a;
//Used for dividing the numbers.
cout << "We will be finding a mean. Enter the amount of numbers that will be entered, the maximum is 12: ";
cin >> a;
cout << "Now enter what numbers you want to find the mean for, because the maximum is 12, if you have less than 12, enter 0 for the rest: ";
f = 0;
for (int i = 0; i < 12; i++) {
cin >> q;
f += q;
}
cout << f / a << '\n';
system("pause");
}
You marked this question as C++.
I recommend you do not use "using", and you should prefer vector over array.
Consider the following approach:
#include <iostream>
#include <vector>
int main(int argc, char* argv[])
{
std::cout << "We will be finding a mean." << std::endl
<< "Enter numbers, and press ^d when complete.\n"
<< std::endl;
// Declare a vector to hold user entered int's
std::vector<int> intVec;
// the vector automatically keeps track of element count
do {
std::cout << "number: "; // prompt
int t = 0;
std::cin >> t; // use std::cin,
if(std::cin.eof()) break; // ^d generates eof()
intVec.push_back(t);
}while(1);
// there are several way to sum a vec,
// this works fine:
int sum = 0;
for (auto i : intVec) sum += i;
std::cout << "\n sum : " << sum
<< "\ncount : " << intVec.size()
<< "\n mean : " << (sum / intVec.size()) << std::endl;
return(0);
}
You can enter single item per line (neatness counts).
You can enter multiple integers separated by white space, but the above will give back a prompt for the integers already entered.
^d - generates an end of file input.
... press and hold 'Control' key and letter 'd' at same time
Note - does not handle error input - try entering a 'number' as 'num' string.
The accepted answer is definitely the most efficient way to transform your code using arrays, but one thing I would add is that in C++ dividing an integer by another integer can only ever result in an integer, and because you're trying to get the mean, it seems like you'd want to have the result in decimals, so you need to do one of two things:
Declare sum as a float for the purposes of diving it by totalNums to get the mean.
Cast one of the integers to either a float or a double so that the decimals won't get truncated, so the last cout statement would look like this:
cout << "The mean is: " << (double)sum/totalNums << endl;
In C++ the default for precision is 6, but you can change the number of decimal points that are displayed by adding #include <iomanip> and using the setprecision( ) function in the iomanip, which you can just add in the same output line:
cout << setprecision(x) << "The mean is: " << (double)sum/totalNums << endl;
where x is whatever precision you want.
If you want to try using dynamic memory
This is definitely not necessary for what you're doing, but it's interesting stuff and good practice!
One more thing is that if you want to be able to have the user enter integers indefinitely, you can dymanically allocate memory during runtime by declaring a array of pointers to integers (so it's an array of address locations instead of an array of integers) and some sentinal value so they can decide when to stop. That code would look like:
#include <iostream>
#include <iomanip>
using namespace std;
main( ) {
const int ARRAY_SIZE = 200;
const int SENTINAL = -999;
int totalNums = 0;
int sum = 0;
//declare an array of pointers to integers so
//the user can enter a large number of integers
//without using as much memory, because the memory
//allocated is an array of pointers, and the int
//aren't allocated until they are needed
int *arr[ARRAY_SIZE];
cout << "We will be finding a mean." << endl;
cout << "Enter integers (up to 200) or enter -999 to stop" << endl;
//add a conditional into the for loop so that if the
//user enters the sentinal value they will break out
//of the loop
for (int c = 0; c < ARRAY_SIZE; c++) {
//every time you iterate through the loop, create a new
//integer by using the new keyword using totalNums as
//the index
arr[totalNums] = new int;
cout << "Enter integer: ";
//input into the array of pointers by dereferencing it
//(so it refers to what the pointer is pointer to instead
//of the pointer)
cin >> *arr[totalNums];
if (*arr[totalNums] == SENTINAL)
break;
else {
sum += *arr[totalNums];
totalNums++;
}
}
cout << setprecision(3) << "The mean is: " << (float)sum / totalNums << endl;
}
When I'm trying to run the program and execute it the for loop doesn't repeat of an adequate form, when I'm trying to execute it appears me this:
Enter a number:
5.6
Enter a number:
Enter a number:
Enter a number:
Enter a number:
Enter a number:
Enter a number:
Enter a number:
Enter a number:
Enter a number:
I tried to search some information about this problem, but I don't found anything. I know that is a foolish question but I don't know where else to turn. A help is appreciated.
I left you my code:
#include <iostream>
using namespace std;
int main (void){
int num, sum;
float average;
for(int i=0; i<10; i++){
cout << " Enter a number: " <<endl;
cin >>i;
sum += num;
}
average = num / 10;
cout << " The total average is:\n " << media <<endl;
}
cin fails its formatted input operation. It was expecting an integer, but you entered into it a floating point number. Hence, it failed. change the input to a float or double.
A couple of more problems with your code:
You can write int main(), rather int main(void). The void isn't quite useful here
Always initialize your variables before use
Sometimes, check for cin failures and report errors if need be
Corrected code...
#include <iostream>
using namespace std;
int main (){
int num = 0, sum = 0;
float average = 0;
for(int i=0; i<10; i++){
cout << " Enter a number: " <<endl;
if(!(cin >> num)){ //you can also use a while loop to force requirement of proper input
cin.clear();
cin.ignore(100000, '\n');
// you can print an error message here
}
else
sum += num;
}
average = static_cast<float>(sum) / 10;
cout << " The total average is:\n " << average <<endl;
}
See Why would we call cin.clear() and cin.ignore() after reading input?
You have three things that ain't correct:
First of all, you have to initialize sum before using, like so int sum = 0;.
Second of all, the entered number has to be saved in a variable. You can't use i as that variable 'cause it's you loop iterator, therefore you can use num.
Last of all, media has no meaning in your program. and i know you meant to use average.
After correcting all of these, your program should look like this one:
#include <iostream>
using namespace std;
int main (void){
int num, sum=0;
float average;
for(int i=0; i<10; i++){
cout << " Enter a number: ";
cin >>num;
sum += num;
}
average = num / 10;
cout << " The total average is:\n " << average <<endl;
system("pause");
}
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.