I have this code and its job is to ask the user if how many elements they would like to enter in the array - the user then enters their desired elements - the elements are integers -then the program solves for the sum of the entered numbers.
Here's the code:
#include <iostream>
using namespace std;
int main()
{
int arr[20], i, n, sum=0;
cout<<"How many elements you want to enter?: ";
cin>>n;
cout<<"Enter any "<<n<<" elements in Array: ";
for(i=0;i<n;i++)
cout<<"How many elements you want to enter?: ";
cin>>n;
cout<<"Enter any "<<n<<" elements in Array: ";
for(i=0;i<n;i++)
{
cin>>arr[i];
}
cout<<"Sum of all Elements are: ";
for(i=0;i<n;i++)
{
sum=sum+arr[i];
}
for(i=0;i<n;i++)
{
cout<<sum;
getch();
}
I doesn't seem to work and the program doesn't run, so I can't put the actual output.
Expected output would be the sum of all the elements (integers) that the user entered.
Does it have to be an array? you can do it in a simpler way like this:
cout << "Enter number of elements\n";
cin >> n
cout << "Please enter the elements \n"
int temp = 0;
int sum = 0;
for(int i = 0; i<n ; i++){
cin >> temp;
sum+=temp;
}
cout << "Sum is: " << sum << endl;
One thin you need to note, you did not restrict the user to the max array size .. say he/she said 21 then you'll have an overflow which produces error.
Since you're using C++, I would suggest you go with vectors, or use the simple way I stated above.
Basic advice: design as you go, and at each stage, use a print-out to tell you what values are entered.
cin >> n;
cout << "Please enter " << n << " values to sum: " << endl;
for(i=0;i<n;i++)
{
cin >> arr[i];
cout << "value #" << i << ": " << arr[i] << " entered." << endl;
}
You basically want to move on to the next stage of processing only when you're sure that your program works for entering the initial data. Take each stage of processing one at a time, and output what the current stage is. This makes it much easier to work out which stage of processing is causing an error. You can cut back on the print commands later on once it's working as intended, but I'd recommend leave then in there but commented out. Sometimes incorrect inputs cause errors again, and it's handy to re-enable the debug prints to tell you what's going on.
Here is the program for your problem description.It takes input from the user to how much elements you want to enter into the array then it take elements and saved in an array then calculates the sum of array elements.
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int arr[20],i,n,sum=0;
cout<<"How many elements you want to enter: ";
cin>>n;
cout<<"Enter any "<<n<<" elements in Array: ";
for(i=0;i<n;i++)
{
cin>>arr[i];
}
cout<<"Sum of all Elements are: " << endl;
for(i=0;i<n;i++)
{
sum=sum+arr[i];
cout << "sum of a[" << i << "] = " << sum << endl;
}
cout<< "the sum of all the elements (integers) that the user entered = " << sum;
getch();
return 0;
}
Now this program gives the information sum of a[i] elements is and so on to the end of the loop.
It is helpful to show the output or error message.
Try to convert cin into an integer or float for:
cin>>arr[i];
Related
Hey am trying to run this code but the for loop executes only once.
Removing the line cout< fixes the problem but I need the ans to be precise to 15 decimal places.
here's the code
int n,i;
cin>>n;
double a[n];
for(i=0;i<n;i++){
cin>>a[i];
a[i]=(a[i]/100);
cout<<fixed<<setprecision(15)<<a[i];
}
for(i=0;i<n;i++) {
cout<<a[i];
}
First things first
Use of variable length arrays (VLAs) is not standard C++. It is supported by some compilers as an extension. If you are allowed to use std::vector, use
std::vector<double> a(n);
If you are not allowed to use std::vector, use
double* a = new double[n];
and make sure to use
delete [] a;
before the end of the funtion.
Suggestion to help you diagnose the problem
Add appropriate prompts before entering data and messages to indicate what was read.
for(i=0;i<n;i++)
{
cout << "Enter number for a[" << i << "]: ";
cin>>a[i];
a[i]=(a[i]/100);
// Make sure to add endl at the very end.
cout<< "Value of a[" << i << "]: " << fixed << setprecision(15) << a[i] << endl;
}
I am trying to write a program in which a user will be prompted to enter an integer 3 times. After each integer, a sum will be displayed after the input. Then, with the second and third integers, the numbers should be added onto the initial sum within a loop. Here is what I have done:
#include <iostream>
using namespace std;
int main () {
double number=0, total=0;
for (double n=0; n<3; n++){
cout << "Enter an integer: ";
cin >> number;
cout << "Sum is: " << number <<endl;
total+=number; }
}
This is the output so far:
Enter an integer: 2
Sum is: 2
Enter an integer: 3
Sum is: 3
Enter an integer: 4
Sum is: 4
The goal is for the integers to continue to add to the sum until the loop is done. This is the output that I am trying to achieve:
Enter an integer: 2
Sum is: 2
Enter an integer: 3
Sum is: 5
Enter an integer: 4
Sum is: 9
Any help would be appreciated, as I am confused on how to solve this part, and it is the only part I need to figure out in order to complete it. Thanks for taking the time to read this!
cout << "Sum is: " << number << endl;
In this line you are printing the current number, not the total. You need to use total instead.
Also move total += number; before the previous line. Else you will be one step behind when displaying.
Thus your code should look like this:
#include <iostream>
using namespace std;
int main () {
double number=0, total=0;
for (double n=0; n<3; n++){
cout << "Enter an integer: ";
cin >> number;
total+=number;
cout << "Sum is: " << total << endl;
}
}
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.
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");
}
So as I explained in the title i'm having trouble trying to get the sum of an array. I've just now learned how to create dynamic arrays and I did some searching on how to calculate the sum. I don't believe I fully understand what is going on to calculate the sum.
// Final Grade Calculator
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int main(){
double minor, quiz, major;
int minorG, quizG, majorG;
minorG = 0;
cout << "Final Grade Calculator" << endl;
cout << "Input minor grade weight percent." << endl;
cin >>minor;
cout << "Input quiz grade weight percent." << endl;
cin >>quiz;
cout << "Input major grade weight percent." << endl;
cin >>major;
// Three grade categories
minor = minor/100;
quiz = quiz/100;
major = major/100;
for(int i = 1; i <=10; i++){
cout << "Input a minor grade. (Max=10)" << endl;
cin >>minorG;
int *minorGA = new int[minorG];
minorG+= minorGA[minorG];
cout << "Currently: " << i << " Grade(s)." <<endl;
}
cout << "Minor Sum: " << minorG << endl;
return 0;
}
This is what I have so far and the trouble I am having is within the for loop which is where my array is and where I am trying to get the sum of it. When I compile and run I get a sum of 138,427. Any help would be greatly appreciated!
I think you're over-complicating things with dynamic arrays. I'll explain what you're doing, and try to provide help for what I think you're trying to do.
In your code int* minorGA = new int[minorG]; you are allocating memory for minorG amount of ints. There are two problems here:
You are accessing an element outside of the memory you allocated. When you allocate 10 elements, you can access elements 0-9. Trying to access 10 is undefined behaviour (you are trying to access parts of memory that could contain anything).
The values stored in this array are just whatever is in memory, so when you are attempting to increment minorG by the amount of one of these, it's just whatever is in memory at the time.
A separate problem is that you are not deallocating the memory, but some might argue that it isn't really a problem.
You should just be able to have the following to perform what I think you're trying to do:
for (int i = 0; i < 10; ++i)
{
int inputtedNumber = 0;
cout << "Enter a number" << endl;
cin >> inputtedNumber;
// add that number to some tally:
finalTally += inputtedNumber;
}
Or if you are trying to store the elements in an array, you can use the following:
const int maxElements = 10;
int grades[maxElements] = {}; // this will construct all elements with 0. Without this, the elements may contain any number.
for (int i = 0; i < maxElements; ++i)
{
int inputtedNumber = 0;
cout << "Enter a number" << endl;
cin >> inputtedNumber;
// Store the number
grades[i] = inputtedNumber;
}
In saying that, it will be better to use std::vector (knows its size, handles memory for you, can grow):
std::vector<int> grades;
// Allow the user to enter as many numbers as they'd like
for (;;)
{
int input = 0;
cout << "Enter a number" endl;
cin >> input;
// Store the number. Will continue to grow
grades.push_back(input);
}