Another While loop or so I think

#include <iostream>

using namespace std; 


int my_sum_less_than(int x)
{
	int y, sum = 0;
	
	while( x <= y )
	{
		sum = x + y;
	}

}

void test_function( int input, int right_answer )
{
	int answer;

	cout << "Calling my_sum_less_than with input " << input << "..." << endl;
	answer = my_sum_less_than( input );

	if( answer == right_answer )
	{
		cout << "...CORRECT (answer is " << answer << ")" << endl;
	}
	else
	{
		cout << "...ERROR, answer was " << answer << ", should have been " << right_answer << endl;
	}
}

int main( )
{

	test_function( 6, 21 );
	test_function( 0, 0 );
	test_function( 11, 66 );
	test_function( -100, 0 );

	system("pause");
	return 0; 
}

I'm trying to get the function to return the sum of all the whole numbers that are positive numbers less than or equal to that number that number being the parameter that was placed in. I'm not looking for the completed version even though it help out a lot but I'm looking for a clear explanation as to what I'm missing and what I clearly left out.

If you do put a completed version (hopefully it stays the same as the one I put up just with the missing things) for some reason please point out the things that were missing and why they go their I want to come out of this learning my mistakes please and thank you - Ako
Also I'm trying to get my own pow() going but I can't figure out how to check when my x = 32 and it's raised to y = 0 the answer = 1
int my_pow( int num, int pow)
{
	int num1 = num;
	while( pow >= 2)
	{
		num = num1 * num;
		
		if (pow == 2)
		{
			return num;
		}
		pow--;
	}
	
	return 1;
}

I weaseled my way out of it for now but I know it's wrong may I get some help on that as well. As to how to check such an unusual case.
You need a selection algorithm it seems for your POW problem. Try using if-else or switch:
1
2
3
4
5
6
7
8
9
10
11
12
switch (pow)
{
    case 0:
        return 1;
        break;
    case 1:
        return num;
        break;
    default:
        // perform regular operation here.
        break;
}

Last edited on
I just figured out the first problem as well. You are not keeping a 'running total' of your sum as you are adding your numbers. You will need to change the line
sum = x + y;

to
sum += x + y

Hope this helps!

EDIT: Sorry, that didn't really solve the problem in question. You don't need another while loop, you need to change your while loop to a FOR loop

for(int i =0; i < x; i++)

The final syntax for you function should be this:
1
2
3
4
int sum = 0;

for(int i =0; i <= x; i++)
      sum += i;


Erase int y altogether that is what the iterator i is for.

Sorry if I caused you confusion. I think I understand your issue better now. Hope THIS helps ^_^

Last edited on
Topic archived. No new replies allowed.