Programming help Loop adding - c++

I know this probably really simple but Im not sure what im doing wrong...
The assignment states:
For the second program for this lab, you are to have the user enter an integer value in the range of 10 to 50. You are to verify that the user enters a value in that range, and continue to prompt him until he does give you a value in that range.
After the user has successfully entered a value in that range, you are to display the sum of all the integers from 1 to the value entered.
I have this so far:
#include <iostream.h>
int main () {
int num, sum;
cout << "do-while Loop Example 2"
<< endl << endl;
do {
cout << "Enter a value from 10 to 50: ";
cin >> num;
if (num < 10 || num > 50)
cout << "Out of range; Please try again..."
<< endl;
} while (num < 10 || num > 50);
{
int i;
int sum = 0;
for (num = 1; num <= 50; num ++)
sum = sum + num;
}
cout << endl << "The sum is " << sum << endl;
return 0;
}
Im just not sure exactly what i'm doing wrong... I keep getting the wrong sum for the total...

Your loop conditions are wrong.
First, you should use a separate variable as your index (in fact you already declared one using "int i" earlier).
Second, your upper limit shouldn't 50, it's whatever the user entered.
So you want to change all "nums" in the loop to "i", and the "50" to "num".

Actually, you can simplify the for loop into:
sum = ((num+1)*num)/2;
Credits to Carl Friederich Gauss. :D

The Corrected code is
#include <iostream.h>
int main () {
int num;
cout << "do-while Loop Example 2"
<< endl << endl;
do {
cout << "Enter a value from 10 to 50: ";
cin >> num;
if (num < 10 || num > 50)
cout << "Out of range; Please try again..."
<< endl;
} while (num < 10 || num > 50);
//<----Removed the extra set of {}
int i,sum=0;//<---- Changed the declaration here
for (i= 1; i <= num; i++) //<----Change Here
sum += i;
cout << endl << "The sum is " << sum << endl;
return 0;
}

Let me make sure I understand this correctly, your assignment asks for a user input for a given number and store it in num and then display a running sum of 1 up to num?
If that's the case, inside your loop you override the user's input of num when you call num = 1. You'll just calculate the running sum of 1-50 every time.
To correct that, you need to use a different variable to keep incrementing, i.e. count or the variable i since it's already been declared. Then you should loop up from i to num as long as i <= num.
Other than that, I cannot see any problems and it should work correctly.
Note to add about a good investment:
It would definitely be worth while to see if the IDE you are developing in has a debugger you can use. Debugging is a great tool to help figure out why your code is not being executing as it is intended to.
If there is no debugger (which would surprise me) might I suggest my go-to alternative method of stepping through the for loop on a sheet of paper and compare the sum to another hand-written solution already solved, i.e. num = 5 sum = 1+2+3+4+5 = 15
Hope this helps.

The for loop should be:
for (int x = 1; x <= num; x++)
{
sum += x;
}

#include <iostream.h>
int main () {
int num, sum; // here you define (but don't initialize) one variable named sum.
[ ... ]
{ // here you start an inner scope.
int i;
int sum = 0; // here you define *another* `sum`, local to the inner scope.
for (num = 1; num <= 50; num ++)
sum = sum + num; // here you add the numbers to the *second* sum.
} // here the second sum goes out of scope.
// and here you print out the first (still un-initialized) sum.
cout << endl << "The sum is " << sum << endl;

Your upper bound is not 50, but the number you entered.
Therefore your summation is from 1 t0 inclusive of your entered number.
Say you enter 10,
logic will be.
You add all the digits from 1 to 10.

Related

How do I add the outputs of a loop?

So in this program, I have to do multiplication in a very tedious fashion and for the second loop, the for loop, I'm multiplying one variable by 2 and the output is the product of that multiplication I am wondering how I could go about taking those output values and adding them together. The code and output of the code are below
#include <iostream>
using namespace std;
int main()
{
cout << "Time to do some Martian Math" << endl;
// variables for math
int righthandnum;
int lefthandnum;
cout << "Please enter two numbers" << endl;
// get values to do the martian math
cin >> lefthandnum;
cin >> righthandnum;
//while loop for right hand number
int i = 0;
while (righthandnum >= 1 ) {
//cout << righthandnum << endl;
//if to find out if any values are odd
if (righthandnum % 2 == 0) {
i -= 1;
}
righthandnum = righthandnum / 2;
i++;
}
int num;
for (num = 1; num <= i; num++) {
lefthandnum = lefthandnum * 2;
//lefthandnum + lefthandnum;
cout << lefthandnum << endl;
}
return 0;
}
The output is
Time to do some Martian Math
Please enter two numbers
50
30
100
200
400
800
Thank you so much for any help!
I don't know if this is what you are looking for but maybe a stack or an array might help you
with the array (the easy way), you make a list of N size for the data as an example:
int values[10];
for(int i = 0; i < 10; i++){
std::cin>>values[i];
}
for(int i = 0; i < 10; i++){
std::cout<<"List element "<<i<<": "<<values[i]<<std::endl;
}
while the stack as I've used it it's a bit more complex and requires pointers.
this is a video (sorry it's in Spanish): https://youtu.be/joAw2jWgZqA

Show the sum in c++ and after that add more sum cpp

Consider a program that asks the user for an integer value greater than 10, say 15. The program should then calculate the sum of all positive values up to 15 and now I need to "show the
current sum after adding each number".
For the first part I made everything like this:
#include <iostream>
using namespace std;
int main()
{
int num = 0;
int sum = 0;
cout << " Please enter how many number you'd like to sum up\n";
cin >> num;
while (num <= 10)
{
cout << "Please enter an integer which is more than 10";
cin >> num;
}
for ( int i = 1; i <= num; i++)
{
sum += i;
}
cout << "The total sum is : " << sum;
But now I dont know what should i do?
It should look like this in the end.
You can do this by outputting the values used in the calculation, along with the 'running' total, inside your summation loop:
for (int i = 1; i <= num; i++)
{
cout << sum << " + " << i << " = " << sum + i << "\n";
sum += i;
}
Feel free to ask for further clarification and/or explanation.

How to assure the loop is entered (C++)

My professor is saying that The while loop runs provided n>=1. But I did not put any value into the variable n so depending on its “default” value, the loop may not be entered. And I'm not sure how to fix what he is talking about!?
#include <iostream>
using namespace std;
int main()
{
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
int n, count;
double sum;
while (n >=1)
{
cout << "Enter a positive integer N (<1 to stop): ";
cin >> n;
sum = 0;
for (count = 1; count <= n; count++)
sum = sum + (1.0/count);
cout << "Sum = " << sum << endl;
}
cout << "Bye! ";
return 0;
}
Here is the line where n is declared
int n, count;
In this case the value of n is unspecified as it is left uninitialized. You should initialize it
int n = 1;
If you always want a loop to run at least once then you want a do...while(); loop. It will always enter the loop on the first iteration and execute the loop body then it will check the while condition to determine if it loops again or exits. A do...while(); has the form of
do
{
statements
} while (condition);
In this case it would save you from having to initialize n before you get the input from the user.
In this case though that doesn't seem like exactly what you want as you want nothing to happen if the user enters a number less than 1. One way you can solve that is to put your output and input into the while loop along with the check for n. This will stop anything from happening if the user enters less than 1 but still allowing you to prompt the usr and get the input on each iteration.
while (cout << "Enter a positive integer N (<1 to stop): " && cin >> n && n >= 1)
{
sum = 0;
for (count = 1; count <= n; count++)
sum = sum + (1.0 / count);
cout << "Sum = " << sum << endl;
}
The problem is that n has not been initialized. Unlike in other languages like Java or C#, primitive variables do not have any pre-defined "default" value. The simply occupy whatever stack space was there previously; for all intents and purposes, the default value of uninitialized variables can be considered "random".
To fix this, simply initialize the variable before entering the loop.
n = 1;
Set n to a value greater than or equal to 1 so the loop is guaranteed to enter. Since you aren't setting it yourself, the default value can be something less than 1 meaning that the look has a chance, but isn't guaranteed to fire.
int n = 1
Also, you should set count = 0 in your for loop, because if n and count is equal to each other, the for loop automatically breaks and doesn't execute at all, leaving sum at 0.
To make sure your dividing by 0, set count to count + 1.
for (count = 0; count <= n; count++)
sum = sum + (1.0 / (count + 1) );
You need simply to use another kind of loop that is the do-while loop. For example
do
{
cout << "Enter a positive integer N (<1 to stop): ";
cin >> n;
sum = 0;
for (count = 1; count <= n; count++)
sum = sum + (1.0/count);
if ( n > 0 ) cout << "Sum = " << sum << endl;
} while ( n > 0 );
cout << "Bye! ";
And instead of the declaration
int n, count;
you should use declaration
unsigned int n, count;
You could else check whether the input is valid. For example
if ( !( cin >> n ) || n == 0 ) break;
Taking this into account you could use also the following kind of loop
while ( true )
{
cout << "Enter a positive integer N (<1 to stop): ";
unsigned int n;
cin >> n;
if ( !( cin >> n ) || n == 0 ) break;
sum = 0;
for (unsigned int count = 1; count <= n; count++)
sum = sum + (1.0/count);
if ( n > 0 ) cout << "Sum = " << sum << endl;
}
cout << "Bye! ";

Finding the highest number in a set of numbers the user enters

I bought the textbook C++ How to program 9th edition and I have come across a question that I am just stumped on, even though it is probably pretty simple. The question all summed up is this: "Use a while statement to determine and print the largest number of 10 numbers entered by the user". But here is the part that stumps me. The question wants me to use only 3 variables. counter, number, and largest. I know to make counter variable go up by 1 for each number entered until it gets to 10, and I know the number variable is used for input. I just can't seem to find out how to use the largest variable, or how to check to see what value is the largest without using other variables. This is all I have so far. Right now I put a break in the code so it wouldn't be an infinite loop.
UPDATED CODE
#include <iostream>
using namespace std;
void main()
{
int counter = 0;
int number = 0;
int largest = 0;
cout << "Please enter up to 10 numbers and I will print the largest one on the screen.\n\n";
while (counter <= 10)
{
cout << "Number: ";
cin >> number;
counter++;
if (number > largest)
{
largest = number;
}
else if (counter == 10)
{
cout << "The largest number was: " << number;
break;
}
}
}
cout << "The largest number was: " << number;
should be
cout << "The largest number was: " << largest;
Inside the while loop, if number is greater than largest, then set largest = number.
Then at the end you can output largest.
Solution(you don't even need a while loop)
#define MAX_NUM 8
//user input goes in myints
int myints[MAX_NUM] = {3,7,2,5,6,4,9};
// using default comparison:
std::cout << "The largest element is " << *std::max_element(myints,myints+MAX_NUM) << '\n';
Other Solution using int arrays even though you can replace int array with one variable
int main()
{
int largest = 0;
int myints[10] = {3,7,2,5,6,4,9,7,2,6};
for(int i =0 ; i< 10;i++)
{
if (myints[i] > largest)
{
largest = myints[i];
}
}
cout << largest << endl;
return 0;
}
Compiled Code
Second Compiled Code
You just need to add in while loop checking is the number you entered bigger than largest. If it is you just store it in largest. And actually you are entering 11 numbers because you count from 0 to 10. Just set counter to 1 or while(counter < 10)
int counter = 1;
int number = 0;
int largest = 0;
cout << "Please enter up to 10 numbers and I will print the largest one on the screen.\n\n";
while (counter <= 10)
{
cout << "Number: ";
cin >> number;
counter++;
if (largest < number)
{
largest = number;
}
}
cout << largest << endl;

Adding consecutive integers from an input (Translated from Python to C++)

I'd like to request some help on my HW. I think I'm really close to figuring this out. Our CompSci class is currently shifting from learning Python to (introductory) C++. Since the two are vaguely similar, we've been advised, since we're beginners, to code the problem in Python (which we're very familiar with) and to translate it into C++ using the basics we just learned. The problem to solve is a simple "add the consecutive integers from 1 to that number, given a positive integer input." So an example would be:
>>Enter a positive integer: 10
>>1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
The Python code (this was successful) that I'm attempting to translate into C++ is:
num = int(raw_input("Enter a positive integer: "))
sum = 0
for i in range(1, num):
sum += i
print i, "+",
print num, "=", sum+num
And my unsuccessful C++ code:
#include <iostream>
using namespace std;
int main()
{
int num;
int sum;
int i;
sum = 0;
cout << "Please enter a positive integer: " << endl;
cin >> num;
for (i=0; 1 <= num; i++)
{
sum = sum + i;
cout << i << "+" << endl;
}
cout << num << "=" << sum + num << endl;
return 0;
}
But the output is simply an infinite, non-ending addition sequence from 0 to infinity, going top to bottom. Even worse is that it did not print in a straight line like I want it. As you can see, I quite literally tried to translate it word-for-word; I thought that'd be foolproof. Something must be wrong with my for loop. Since C++ doesn't have a class of its own for "range" like Python does, I thought the middle condition statement ("1 <= num;") would act as the range. Why didn't my "=" sign print out? And I don't understand why it won't terminate when it reaches "num." Think you can help? I thank you in advance for the replies.
Fixed code:
#include <iostream>
using namespace std;
int main()
{
int num;
int sum;
int i;
sum = 0;
cout << "Please enter a positive integer: " << endl;
cin >> num;
// Here you had 1 <= num which was always true for positive num
// and it did not depend on value of i.
for (i = 1; i < num; ++i)
{
sum = sum + i;
cout << i << "+"; // Here you had endl which produced newline characters.
}
cout << num << "=" << sum + num << endl;-
return 0;
}
This:
for (i=0; 1 <= num; i++)
should be:
for (i=0; i <= num; i++)
try this.
#include <iostream>
using namespace std;
int main()
{
int num;
int sum;
int i;
sum = 0;
cout << "Please enter a positive integer: ";
cin >> num;
for (i=0; i < num; i++)
{
sum = sum + i;
cout << i << " + ";
}
cout <<num << " = " << sum+num << endl;
return 0;
}
I don't really know Python, but the code
for i in range(1, num):
looks really similar to
for (int i=1; i <= num; ++i)
or is it possibly
for (int i=1; i != num; ++i)
which looks more like C++?
loop in c++ are most basic than python, the for loop is more simpler, it is based on the three expression: initializer expression, the loop test expression, and the counting expression. In particular what is wrong in your code is the test expression. Remember that the loop is executed if the test expression is true. You need to loop if the condition i<num is true. Your loop is never ending because num is always >= 1, or as you wrote 1 <= num always.
To print everythig on a line don't use endl