need help with this question

I need help with what this code would look like, if someone can write this out for me that would be awesome! Thanks!


Prompt the user for a number x and output the sum of all numbers from 1 to x. If the number entered is less than zero, output an error message.
What have you written so far? Make sure your code is [code]between code tags[/code] so that it has line numbers and syntax highlighting, as well as proper indentation.
 
Prompt the user for a number x

Ask the user to input a number x.

output the sum of all numbers from 1 to x
Use a running total inside a loop with a condition that does not exceed the number the user inputted.

If the number entered is less than zero, output an error message.
Use a validation method to ensure the number is not a negative number (less than zero).

It is up to you to figure out what this code would look like. Give it some work, then comeback with a specific question. Remember, just like programming, vague questions will get vague answers. Good luck.

something like this.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
int main()
{
	signed int n = 0;
	unsigned int current = 0;
	std::cout << "How many numbers ?\n";
	std::cin >> n;
	if (n > 0)
	{
		signed int* array = new signed int[n];

		while (current < n)
		{
			signed int tmp = 0;
			std::cout << "Enter the n." << current + 1 << " number\n";
			std::cin >> tmp;
			array[current++];
		}
		current = 0;
		while (current < n)
		{
			std::cout << array[current++] << std::endl;
		}
		delete[] array;
		array = nullptr;
	}
	else
	{
		std::cout << "ERROR!\n";
	}
	return EXIT_SUCCESS:
}
@Ericool: you completely misread the assignment.

Also, at least use good practice when trying to teach others: don't use new in your code.

Also, please don't try to post full solutions to obvious homework questions unless you know it won't just get copypasted.
Last edited on
@LB my bad .
This was a problem that a friend and myself were trying to solve. We kept getting stuck on how to obtain the sum from numbers 1 to x, x being any number.

Thanks anyway.
Butch wrote:
We kept getting stuck on how to obtain the sum from numbers 1 to x, x being any number.
A basic for loop adding the current index to a variable should be all it takes for naive approach. There's also a famous formula for calculating that particular sum without using a loop.
Yep Gauss n*(n+1)/2 if I am not wrong
Topic archived. No new replies allowed.