C++ add 1+2+3+...+N - c++

I've been having trouble with a problem from my C++ book. It wasn't required to do, but I want to get it to work:
Sum of numbers
Write a program that asks the users for a positive integer value and that uses a loop to validate the input.* The program should then use a second loop to compute the sum of all the integers from 1 up to the number entered. For example, if the user enters 50, the loop will find the sum of 1, 2, 3, 4, ... 50.
*I'm not asking for this first loop, just the second. But if you feel like coding it go ahead.
It's pretty simple to write a program that decreases a number until it reaches one:
#include <iostream>
using namespace std;
int main()
{
int number;
cout << "Enter a number: ";
cin >> number;
while(number >= 1)
{
cout << number << " ";
number--;
}
system("pause"); //I usually go with cin.get() but my current
//compiler doesn't handle it
return 0;
}
But if you to add "number - 1" to a number, the number becomes bigger and now number - 1 will increase from thereon. For example, 7 + 6 = 13, 13 + 12 = 25, 25 + 24 = 49, etc. Here's the program I am trying to adapt to make work:
#include <iostream>
using namespace std;
int main()
{
int number;
cout << "Enter a number: ";
cin >> number;
for(count = 1; count <= number; count++)
{
number += number - 1;
}
cout << "The sum is" << number << endl;
system("pause"); //
return 0;
}
This is an infinite loop, unfortunately.
Any ideas to how to adapt this program so it satisfies the question? Or links to source code that's already done it before, etc.
EDIT:
So this might be another issue entirely, but my code isn't compiling:
#include <iostream>
using namespace std;
int main()
{
int number, sum = 0;
cout << "Enter a number: ";
cin >> number;
for(count = 1; count <= number; count++)
{
number--;
sum += number;
}
cout << "The sum is" << sum << endl;
system("pause"); //
return 0;
}
EDIT 2: I just got rid of the for loop and changed it to "while(number >= 1)"

Something like this ?
int sum = number;
while (number-- > 0) {
sum += number;
}

I find a for loop neater, so I'll post an example for variety.
int n = Max Number
int sum = 0;
for(int i = 1; i <= n; i++) {
sum += i;
}
And for your compiling problem, unless I'm reading it wrong, you shouldn't be decrementing the number; it's defining what the max number is. Each loop you're incrementing the count, decrementing the number, then comparing them. I can't imagine that will give you anything meaningful. Erase the number--;, and it should work.

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

How to count by three from the number given by the user?

I have to create a program using a for loop that will count by 3 from the given number from the user 20 times. So far this is what i have.
#include <iostream>
using namespace std;
int main(){
int num, newNum, add;
cout << "Enter a number: ";
cin >> num;
for(int count = 0; count < 20; count++){
for(int sum = 0; sum <= count; sum++){
newNum = num * (count +1);
}
cout << num << " ";
}
}
I have no idea where to go from here. I know that i would have to put the number given into a variable like i do with num and i know i would somehow have to store the new number in another variable like i do with newNum. Any help would be appreciated! Also this is what the output should look like in case i did not explain it good enough.
Enter a number: 3
3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60.
And bonus points if you can have the last number end with a period instead of a comma :)
This should work:
int main(){
int num, currentNum, add, newNum;
std::cout << "Enter a number: ";
std::cin >> num;
std::cout << num
for(int count = 0; count < 20; count++){
num += 3;
std::cout << ", " << num;
}
std::cout << " ." << std::endl;
}
Also try to not use using namespace std. It clutters the namespace.
You can add 3 to the number either inside the loop's third statement (you can also have multiple conditions etc.)
for(int count = 0; count <= 20; count++, num+=3){
// ...
}
or inside the loop's code block
for(int count = 0; count <= 20; count++){
num += 3;
}
As for the comma you just need to add it to the output:
cout << num << ", ";
Since you want a dot at the end you need to handle this in an if-else case
if (count < 20)
cout << num << ", ";
else
cout << num << ".";
or a ternary operator:
cout << num << (num < 20) ? ", " : ".";
Bonus points: don't expose the complete namespace (here: std). While in such a small example it's not an issue it may lead to hard to detect bugs later on if you happen to use one or multiple namespaces that offer the same functionality.
OK, we have so far an answer explaining pretty well and another one optimising the if inside the loop away. We still can optimise away one addition, if you count up the num variable directly:
for(auto end = num + 57; num < end; num += 3)
// ^ still one number less, last one follows the loop!
{
std::cout << num << ", ";
}
std::cout << num << '.' << std::endl;
// ^ ^ not much difference, but just outputting a single character
// is more efficient, no need to iterate to find the
// trailing null character...
std::endl not only adds a newline, but flushes the stream immediately (i. e. the so far possibly buffered output is forced to be printed to console). This is especially useful if there's more output to follow, but possibly quite a while later (without flushing, user might see incomplete last line). Admitted, in given case not necessary, as std::cout's destructor will flush anyway, so you could go, too, with the slightly simpler std::cout << num << ".\n"...
Without using the extra variables.
#include
using namespace std;
int main(){
int num, currentNum, add, newNum;
cout << "Enter a nummber: ";
cin >> num;
for(int count = 0; count <= 20; count++){
cout << (num + count * 3);
if(count == 20)cout<<".\n";
else cout<<", ";
}
}
More general solution would be:
#include <iostream>
using namespace std;
int main(){
int num, currentNum, add;
cout << "Enter a nummber: ";
cin >> num;
add = 3;
currentNum = num;
for(int count = 0; count <= 20; count++){
cout << (currentNum); //Print current number
currentNum = currentNum + add; // increase the number
if(count == 20)cout<<".\n"; //if the last one print dot
else cout<<", "; //else place comma
}
}

How to most efficiently take in 10 different numbers from a user, add them to an array, and then output all of those numbers?

New to C++, I'm trying to make a program that takes in 10 different numbers, and it takes all of those numbers and adds them to an array list which prints them out at the end.
My code: (that doesn't work)
#include<iostream>
#include<string>
#include<iomanip>
using namespace std;
int main()
{
int numbers[10];
int input;
cout << "Please enter ten numbers" << endl;
for(int i=0;i<10;i++){
cin >> input;
int numbers[i] = numbers + input;
}
cout << numbers;
}
When I run this and put in all 1's for all ten numbers, I expect to get an output like 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
but instead I get 0x7d88afc45630 which is weird and I'm not really sure why. I think it has to do with how I'm adding the numbers into the array list, which I'm not even sure how to do. I'd also like to be able to return the largest and smallest values of the list, but I need to figure this out first.
int numbers[i] = numbers + input;
It's converting the address the memory for numbers is at to an integer and adding it to input.
Do you just mean
numbers[i] = input;
On top of that, cout << numbers just prints out the memory location of numbers.
You probably want something like:
for (int i = 0; i < 10; i++) {
cout << numbers[i] << endl;
}
Changed the output variable used as you don't need an array for this. Also, you don't need to put the data type before the variable name when assigning a value to it if you already declared that variable. See the modified code below:
#include<iostream>
#include<string>
#include<iomanip>
using namespace std;
int main()
{
int sum = 0;
int input;
cout << "Please enter ten numbers" << endl;
for(int i=0;i<10;i++)
{
cin >> input;
sum += input;
}
cout << sum;
}
If what you mean by "adding to an array" is putting the user input values to an array, just change these parts
int sum = 0;
:
sum += input;
:
cout << sum;
to
int numbers[10];
:
numbers[i] = input;
:
for(int i=0;i<10;i++)
{
cout << numbers[i] << endl;
}

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;

C calculating sum correctly

I can get the sum every time the user inputs an integer until either a negative number or non-integer is inputted. Problem is my sum calculations are off. I.E user putting 1000; sum outputs 1111, then user inputs 2000, it adds up to 3333. Just any advice is appreciated. I'll still experiment around with my coding.
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int j , i = 0, k = 0,number;
double sum = 0;
cout << "Enter Positive integer number: ";
while(cin >> number)
{
cout << endl;
if( number < 0)//test if the number is negative
{
cout << "Ending program since user has input a negative number" <<endl;
break;
}
int temp = number;
int p = 1;
while( temp > 0) //counting number of digits
{
sum = sum+temp; //Sum attempt.
temp /= 10;
p *= 10;
i++;
}
cout << sum << endl;
j = i % 3;
p /= 10;
while( i > 0 )//display integer number with 1000 seperator
{
//this is giving me error
cout << char ((number/p) +'0');
number %= p;
p /= 10;
i--;
k++;
j--;
if ((k % 3 == 0 && i > 0)||(j == 0 && i > 2) )
{
cout <<",";
k = 0;
}
}
cout << endl << endl;
cout << "This program will exit if you input any non-integer characters\n";
cout << "Enter another integer number: ";
}
return 0;
}
It looks like you're trying to output an integer number with commas inserted at 1000 boundaries. ie: 1000000 would be displayed as 1,000,000.
This being the case, the easiest way to approach it might not be involving maths but simply to get a string representation of the int (atoi() for example) and count through that. From the back, count forward three chars, insert a comma, repeat until you run out of string.
The specifics of string handling are left as an exercise for the reader - looks like it's his homework after all. ;-)