Need to fix a simple loop - c++

Okay I need to write a function that takes an integer parameter and prints the sum of each number up to that point. For example, n = 10 would be 1+2+3+4+5+6+7+8+9+10.
int SumOneToN(int n)
{
int x = 0;
while (x <= n)
{
cout << x+(x+1) << " ";
x++;
}
cout << endl;
}
So what's going on here?
1. Set up the function as SumOneToN.
2. Initialize x to 0.
3. Create a while loop that states while x is less than our parameter, we take x, add it to x+1 (so that we get our current x value added to the next one), print it, then we add to x for the loop to go again until we meet the parameter.
That's how I thought it should work, anyways. What actually returns is:
1 3 5 7.. etc
I'm not sure where I went wrong?

Try this :
int SumOneToN(int n)
{
int x = 1, sum=0;
while (x <= n)
{
sum=sum+x;
cout << sum << " ";
x++;
}
cout << endl;
return sum;
}

Why not use some maths an not have the loop in the first place?
i.e.
int SumToOne(int n) {
return (n * (n + 1))/2;
}

int SumOneToN(int n)
{
int sum=0;
for(int x=1;x<=n;x++)
{
sum+=x;
cout << sum << " ";
}
cout << endl;
return sum;
}

Write the "+" sign in the inverted commas and cout x; once before the while loop. If you want to do it by SUM than you have to introduce another variable and the above solutions are fair enough.
#include <iostream>
using namespace std;
int SumOneToN(int n)
{
int x = 1;
cout << x ;
x++;
while (x <= n)
{
cout << " + " << x ;
x++;
}
cout << endl;
}
int main()
{
int x;
cin >>x;
SumOneToN(x);
return 0;
}

You can try this:
int SumOneToN(int n){
int sum=n,x=1;
while(x<n){
cout<<x<<"+";
sum+=x;
x++;
}
cout<<x;
return sum;
}
Note: This wont print an additional '+' after last number.

Hey you are using same variable for Sum & as looping variable
try this code
int add(int n)
{
int sum=0;
for(int i=1;i<=10;i++)
sum=sum+i;
return sum;
}

Related

I want to find the sum of range between two numbers?

#include <iostream>
#include <algorithm>
using namespace std;
void sumrange(int x, int y) {
int sum;
cout << "Enter the first number: ";
cin >> x;
cout << "Enter the second number: ";
cin >> y ;
int bnum = max(x,y);
int snum = min(x,y);
int i = snum;
while (i < bnum) { sum =+ i; i++; }
cout << sum;
}
int main() {
int x, y;
sumrange(x,y);
return 0;
}
I can't get the right answer from my input I tried 1 and 4 and the answer was 3 but it supposes to be 1+2+3+4 which is 10.
Couple of observations:
don't use using namespace std; it is a bad practice and might lead to name conflicts
variable int sum needs to be explicitly initialized before use
sum =+ i should be sum += i
you need to use <= if you want to include the upper bound
take a look at the arithmetic sequence
sumrange function doesn't need parameters, sice they are passed by value int x, y; from your main are not used at all
Following code should do what you want:
#include <iostream>
#include <algorithm>
void sumrange()
{
int x;
int y;
int sum = 0;
std::cout << "Enter the first number: ";
std::cin >> x;
std::cout << "Enter the second number: ";
std::cin >> y ;
int bnum = std::max(x,y);
int snum = std::min(x,y);
int i = snum;
while (i <= bnum) { sum += i; i++; }
std::cout << sum;
}
int main() {
sumrange();
return 0;
}
You have inverted the += sign to =+
It should be sum += i .
sum = +i assigns the number to itself
Edit: you should also initialize sum, stated in the comment
There are 3 problems with your given code snippet.
Problem 1: =+ should be += in the statement:
sum =+ i; //=+ should be +=
Problem 2: The variable sum is uninitialized and so it has a garbage value. Using that garbage value leads to undefined behavior.
Problem 3: Should use <= instead of < in the statement
while (i < bnum) //should be i<=bnum
So the modified(corrected) program looks like below:
#include <iostream>
#include <algorithm>
void sumrange(int x, int y) {
int sum=0;///INITIALIZE sum
std::cout << "Enter the first number: ";
std::cin >> x;
std::cout << "Enter the second number: ";
std::cin >> y ;
int bnum = std::max(x,y);
int snum = std::min(x,y);
int i = snum;
while (i <= bnum) //USED <=
{
sum += i; //USED +=
i++;
}
std::cout << sum;
}
int main() {
int x, y;
sumrange(x,y);
return 0;
}
Alternative solution
Note that you can find the sum without using a loop as shown below:
#include <iostream>
#include <algorithm>
void sumrange(int x, int y) {
int sum=0;//initialize sum
std::cout << "Enter the first number: ";
std::cin >> x;
std::cout << "Enter the second number: ";
std::cin >> y ;
sum = (std::abs(x - y) + 1) * (x + y) / 2; //ADDED THIS
std::cout << sum;
}
int main() {
int x, y;
sumrange(x,y);
return 0;
}
A C++20 solution :
#include <algorithm>
#include <iostream>
#include <numeric>
#include <ranges>
int main()
{
int a{ 0 };
int b{ 0 };
std::cout << "Enter the first number: ";
std::cin >> a;
std::cout << "Enter the second number: ";
std::cin >> b;
auto lower_bound = std::min(a, b);
auto upper_bound = std::max(a, b) + 1; // iota view is exclusive so add 1
auto view = std::ranges::iota_view{ lower_bound , upper_bound };
auto sum = std::accumulate(view.begin(), view.end(), 0);
std::cout << "sum = " << sum << "\n";
return 0;
}
constexpr auto sumrange(const int x, const int y) noexcept {
auto sum = 0;
if (x < y) for (auto i = x; i <= y; ++i) sum += i; else
if (y < x) for (auto i = y; i <= x; ++i) sum += i;
return sum;
}
int main() {
constexpr auto x = 1;
constexpr auto y = 3;
constexpr auto r = sumrange(x, y); // 1 + 2 + 3
std::cout << r << '\n'; // 6
}
Values of the function arguments are not used in this call
int x, y;
sumrange(x,y);
So such a call does not make a sense.
You need in main to ask the user to enter a range of numbers and pass the range to the function.
The task of the function is to return the calculated sum for the specified range in main.
Within the function sumrange the variable sum is not initialized.
int sum;
You need to initialize it to 0.
In this while loop
while (i < bnum) { sum =+ i; i++; }
^^
there is a typo. Instead of the compound assignment operator += you are using the assignment operator = and the unary + operator
Moreover as it follows from your comment you need also to add the value of bnum to the sum.
So the loop should look at least like
while (i <= bnum) { sum += i; i++; }
Pay attention to that in general an overflow can occur. So it is better to declare the variable sum as having the type long long int.
The function and the program can look the following way
#include <iostream>
#include <utility>
#include <algorithm>
long long int range_sum( int x, int y )
{
long long int sum = 0;
auto [first, last] = std::minmax( { x, y } );
do
{
sum += first;
} while (first++ != last);
return sum;
}
int main()
{
int x = 0, y = 0;
std::cout << "Enter the first number: ";
std::cin >> x;
std::cout << "Enter the second number: ";
std::cin >> y;
std::tie( x, y ) = std::minmax( { x, y } );
std::cout << "The sum of numbers in the range ["
<< x << ", " << y << "] is equal to "
<< range_sum( x, y )
<< '\n';
}
The program output might look like
Enter the first number: 1
Enter the second number: 10
The sum of numbers in the range [1, 10] is equal to 55

why do i have to add a new variable in this code

I was trying to write a code that takes two numbers as a input and change the numbers into words in certain rules.
Below is the code I wrote at first, but whatever input I put in, the loop starts from x=0.
#include <iostream>
int main() {
string nums[10] = {"zero","one","two","three","four","five","six","seven","eight","nine"};
int x,y;
cin >> x;
cin >> y;
for (int x = x; x <= y; x++){
if (x <= 9){
cout << nums[x] << "\n";
}
else if (x % 2 == 0){
cout << "even" << "\n";
}
else {
cout << "odd" <<"\n";
}
}
return 0;
}
Below is the second code I wrote and it worked as I wanted to.
#include <iostream>
int main() {
string nums[10] = {"zero","one","two","three","four","five","six","seven","eight","nine"};
int x,y;
cin >> x;
cin >> y;
for (int i = x; i <= y; i++){
if (i <= 9){
cout << nums[i] << "\n";
}
else if (i % 2 == 0){
cout << "even" << "\n";
}
else {
cout << "odd" <<"\n";
}
}
return 0;
}
I found out that if I add a variable, it works as what I wanted too. I found the solution but I don't know why I have to add a variable and why the first one always starts from x=0.
In first sample that you provided you defined a local variable(x) as same name in outer block:
for (int x = x; x <= y; x++)
In fact shadowing of variable take place here and c++ hide the declaration of variable of outer block with same name in nested block.

My loop never ends...and I dont understand why. Any ideas?

I am trying to find out why my loop never ends. I am trying to take two numbers, start with the smallest, and keep divid by 4 until it reaches 0.
#include<iostream>
using namespace std;
int main
{
int x, y, answer = 0;
cout << "dude enter two numbers " << endl;
cin >> x >> y;
//this is trouble statement
for (int num = x; num <= y; num++)
{
while (num != 0)
answer = num / 4;
cout << answer << " ";
}
}
return 0;
}
The condition while (num != 0) is the problem.
As, you are not modifying num in the while loop, hence the value of num would never change.
Hence, the infinite loop.
A few changes in your code will suffice :
#include<iostream>
using namespace std;
int main()
{
int x, y, answer = 0;
cout << "dude enter two numbers " << endl;
cin >> x >> y;
for (int num = x; num <= y; num++)
{
//Created a temporary variable.
int temp = num;
//All operations on the temporary variable.
while (temp != 0)
{
temp = temp/ 2;
cout << temp << " ";
}
cout<<endl;
}
return 0;
}

Recursion help in C++

The assignment is Design and Develop a C++ program to list the first N terms of the Fibonacci series.
The output should look like this:
N=2 1,1
N=2 1,1
N=3 1,1,2
N=4 1,1,2,3
N=5 1,2,3,5
N=6 ....
My problem is that I have written the recursive function below but I'm not sure how to format it so it outputs to screen in the manner above.
#include <iostream>
using namespace std;
//Function Prototype
int fib(int);
int main()
{
for (int x = 0; x < 15; x++)
cout << fib(x) << " ";
cin.get();
cin.get();
return 0;
}
//Definition of fib
int fib(int n)
{
//Return 1 when n is 0
if ( n <= 0 )
return 0;
else if (n == 1)
return 1;
else
return fib(n-1) + fib(n-2);
}
Could someone shed some light on how to get this accomplished?
Thank you.
if you don't care too much about efficiency, a double loop will do
for (int x = 2; x < 15; x++) {
cout << "N = " << x << " ";
for (int y = 2; y <= x; y++)
cout << fib(y) << " ";
cout << endl;
}
How to format?
You have a good start.
Try this as a next step...
for (int x = 0; x < 15; x++)
cout << x << "=" << fib(x) << " " << std::endl;
cin.get();
In my system, I can add to the cout line, compile, and review the output in < 10 seconds. Fast turn around and practice (for you) are your friends.
I would take a different approach. I'd save the already computed Fibonacci values so they are not computed them over and over again, like in a map, and than using that map to print the values.
std::map<int, int> fibs;
int fib(int const n)
{
auto p = fibs.find(n);
if(p != fibs.end())
return p->second;
int f = 1;
if (n > 1)
{
f = fib(n-1) + fib(n-2);
}
fibs[n] = f;
return f;
}
You can then loop through the computed values like this:
for(int n = 0; n < 10; ++n)
{
fib(n);
std::cout << "N=" << n << " ";
for(int i = 0; i <= n; ++i)
std::cout << fibs[i] << ",";
std::cout << std::endl;
}
Since it all does is print the fibonacci number, and the ones before, you just need to add them to your output ...
You can either have an aggregating string that you pass along, that will hold all the temp values, or just call another method that will have temp outputs. (mind you, it's not very efficient though :)
int fib_verbose(int n)
{
//Return 1 when n is 0
if ( n <= 0 )
return 0;
else if (n == 1) {
return 1;
}
else {
int smaller = fib(n-2);
int larger = fib(n-1);
cout << smaller << " " << larger << endl;
return smaller + larger;
}
}
You'll have to sort out the spaces, and formatting, but that's the gist.
Edit:
As per agbinfo comment: removed the 1 printing, and also storing the variables so we don't need to call them twice. (Still, for efficiency, look at Marius's answer :) ).
Here's an example that doesn't recompute values when calling fib for a single value. You can combine Marius's idea to compute the values once even on multiple runs.
The trick is that fib(unsigned&, unsigned) will return the previous fibonacci it has already computed.
#include <iostream>
using namespace std;
unsigned fib(unsigned& m, unsigned n)
{
if (n==0) {
return 0;
}
if (n==1) {
m = 0;
// cout << "0,"; // uncomment if sequence should start with a 0
return 1;
}
unsigned prev;
m = fib(prev, n-1);
cout << m << ",";
return m+prev;
}
unsigned fib(unsigned n) {
unsigned prev;
unsigned f = fib(prev, n);
cout << f;
return f;
}
int main() {
for (unsigned i=2; i<13; i++) {
cout << "N=" << i << " ";
fib(i);
cout << endl;
}
return 0;
}
Will printout:
N=2 1,1
N=3 1,1,2
N=4 1,1,2,3
N=5 1,1,2,3,5
N=6 1,1,2,3,5,8
N=7 1,1,2,3,5,8,13
N=8 1,1,2,3,5,8,13,21

cannot achieve desired output (cout) from a C++ loop

thanks to your help last night I was able to get my program computing my input properly, but now I am have trouble formatting my output properly. This is the problem:
My program should only print "is prime" on lines with prime numbers. But it prints on ever line like this:
http://oi42.tinypic.com/30igbvq.jpg
I cannot for the life of me figure out why it is doing this, all of my functions should work.
Stack I need your help again!
#include <iostream>
using namespace std;
void primecheck(int x); // proto
void countr(int rnm, int lnm); // proto
void prime(int x) // this function finds the prime factors of a number.
{
int lastr = 2;
int count = 0;
while (lastr < x)
{
if (x % lastr == 0)
{
cout << x << " " << lastr << "*";
x /= lastr;
}
else
++lastr;
}
primecheck(x); // calls to check if number is prime, "Is prime"
}
void console(int rnum, int lnum) // this prompts the user for two numbers then stores the answers
{
cout << "please enter two numbers ";
cin >> rnum;
cin >> lnum;
countr(rnum, lnum);
}
void countr(int rnm, int lnm) // this function loops the prime function until all the numbers are computed
{
int i = rnm;
do{
prime(i);
i++;
} while (i <= lnm);
return;
}
int main() // main, calls console then pauses when finished
{
int e = 0;
int r = 0;
console(e, r);
system("PAUSE");
}
void primecheck(int x) // checks to see if then number is prime. if counter is equal to 2 than number is prime.
{
int counting = 0;
for (int a = 1; a <= x; a++)
{
if (x %a == 0)
{
counting++;
}
}
if (counting == 2)
{
cout << x << " is prime " << endl;
}
else
{
cout << x << endl;
}
}
You're using a /= operator in prime(). That's an assignment operator and is modifying the value of x, making x always prime whenever primecheck() is called.