# School assignment using while loops

## Recommended Posts

EDIT: I've fixed it, thanks for the help guys! :D On C++. Yeah.. our teacher basically just gives us homework and tells us to read the book. I've read the book we're supposed to read and it doesn't tell me anything about how to do this, so I've come to you guys for help. Here are the instructions: 1. Prompts the user to input 2 numbers - firstNum and secondNum. Make sure that firstNum is less than secondNum. If it is not, the user should get an error message and be prompted again to enter the values. ... uses while loops to perform the following steps: 2. Output all odd numbers between firstNum and secondNum. 3. Output the sum of all even numbers between firstNum and secondNum. 4. Outputs the numbers and their squares of all numbers between firstNum and secondNum. 5. Outputs the numbers from secondNum to firstNum as a countdown sequence Here is the code I have so far, I'm not sure if it's correct or not:
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
int firstNum, secondNum, squareNum, counter, counterT, counterR, counterU;
int sum = 0;

cout << "The first number must be less than the second number.\n\n";
cout << "Enter 1st number: ";
cin >> firstNum;
cout << "Enter 2nd number: ";
cin >> secondNum;

counterT = secondNum;
counterU = secondNum;
if (secondNum % 2 == 1)
{
counter = secondNum - 2;
counterR = secondNum - 1;
}
else
{
counter = secondNum - 1;
counterR = secondNum - 2;
}

if (firstNum < secondNum)
{
cout << "Odd numbers: ";
do
{
cout << counter << " ";
counter -= 2;
} while(counter >= firstNum);
cout << "\n";
cout << "Sum of even numbers: ";
do
{
sum+=counterR;
counterR -= 2;
} while (counterR >= firstNum);
cout << sum;
cout << "\n";
cout << "Squares of numbers: ";
do
{
cout << (counterU * counterU) << " ";
counterU--;
} while(counterU >= firstNum);
cout << "\n";
cout << "Countdown: ";
do
{
cout << counterT << " ";
counterT--;
} while(counterT >= firstNum);
cout << "\n";
}
else
cout << "Your first number is not less than your second number.\n";

system("pause");
return 0;
}

[Edited by - Ultimatepuff on July 21, 2009 4:05:44 PM]

##### Share on other sites
What specifically are you having trouble with?

##### Share on other sites
Quote:
 Original post by HapticWhat specifically are you having trouble with?

I don't know how to do parts 2-4, and I'm not sure if I did part 5 right either.

##### Share on other sites
That isn't a complete program, I think you've only pasted as fragment of what you really have, if it's much longer than that though then I recommend you use source tags intead.

##### Share on other sites
"int firstNum, secondNum, oddNum, sum, evenNum, betweenNum, squareNum, counter;
counter = secondNum;"

counter = secondNum is a bug because secondNum is initialized. This would cause
the program to crash

##### Share on other sites
Quote:
 Original post by dmatterThat isn't a complete program, I think you've only pasted as fragment of what you really have, if it's much longer than that though then I recommend you use source tags intead.

Well a fragment is actually all I have, I don't know where to start on the rest because I'm new/suck at programming like that.

##### Share on other sites
Well you already have a while loop there that goes through all of the numbers (albeit backwards), so for question 4, why not just add a few lines that calculates and outputs the square of the current number.

To calculate if a number is odd or not you need to divide it by 2 and get the remainder. In C, this is done with the % operator. So 3%2 = 1.
If the answer is zero, it's even, if it's 1 its odd. You just need to add this condition to your loop.

As a side note - you are setting the value of 'counter' before you set the value of secondNum which is a bug.

##### Share on other sites
Quote:
 Original post by tnutty"int firstNum, secondNum, oddNum, sum, evenNum, betweenNum, squareNum, counter; counter = secondNum;"counter = secondNum is a bug because secondNum is initialized. This would causethe program to crash

it wouldn't cause a crash, it would just set counter to an uninitialized value (secoondNum could be any number), but it won't crash.

##### Share on other sites
First, might I say that being new to programming and looking for help would indicate you do not suck. Look at what you have not as incomplete, but small portions that are complete.

The way you seem to be setting up all the while loops in the if statement is a good way to go. Have you learned if/else blocks yet?

Also, as I have read my fair share of C++ textbooks I can understand there is a difference between syntax and explaination of how things work.

As others have pointed out 'counter = secondNum' is bugged, but for two reasons:
1. unless you specifically assign a value to your variables, the value that is stored is whatever happened to be at that memory location (usually refered to as garbage)

2. The second bug is a logic error. You assigned counter secondNum's value before the user actually defined what secondNum was equal to so you really have no control. Try assigning the value of secondNum after the user enters it to counter. That way you "know" that it is properly defined (assuming the user input was valid).

You have a good start. Just keep asking questions.

##### Share on other sites
Exactly. Your code will not work because counter will not be equal to secondNum because the assignment is done before secondNum itself has a value!

int firstNum, secondNum, oddNum, sum, evenNum, betweenNum, squareNum, counter;counter = secondNum; //This is your problem right here

If you look at the code, you will see that you have declared all of those variables, however the user hasn't entered the two numbers yet, so counter will not be equal to the value of secondNum later on.

Just think about where you should move the assignment so that counter has the proper value of secondNum after the user has entered it.

For #2, you can see whether or not a number is odd by using the % operator, which returns the remainder between two numbers. Knowing that any even number divided by 2 has a remainder of zero, it is a simple task to see whether or not a number is odd or not.

All in the same loop, you can output all of the odd numbers by seeing if the remainer between the number and 2 is not 0, and if it is zero, then it is an even number, and for problem #3, you can add it to the sum variable (remember to initialize that variable at 0!).

Knowing that, I am sure you can figure out problem #4. You can either implement your own function for squaring numbers (as there is no operator for squaring a number in C++) or you can use the function in the math library.

##### Share on other sites
Quote:
 Original post by HapticWell you already have a while loop there that goes through all of the numbers (albeit backwards), so for question 4, why not just add a few lines that calculates and outputs the square of the current number.To calculate if a number is odd or not you need to divide it by 2 and get the remainder. In C, this is done with the % operator. So 3%2 = 1. If the answer is zero, it's even, if it's 1 its odd. You just need to add this condition to your loop.As a side note - you are setting the value of 'counter' before you set the value of secondNum which is a bug.

I'm a little confused about % operators. Can someone provide an example within a code or something?

##### Share on other sites
if you remember doing division in elementary school you often were left with remainders. this is where the % operator comes in as it returns the remainder of the division between the two numbers.

Now figure out what you need to divide by to figure out if it's an odd or even number and you've solved one of your problems.

If you don't remember/know much of your math; a square is a number times itself;

once you solve the odd question you should be able to change some minor things to get the sum of all even numbers.

I would tackle this problem by solving each individual problem then combining them together.

##### Share on other sites
% returns the 'remainder' of a division.

So for example, if you divide 11 by 2:
2 goes into 11 five whole times - with 1 remainder.
So 11%2 will return 1.

cin >> number;// if i divide number by 2, what will the remainder be?int rem = number % 2; if(rem == 0){    // number is even because 2 fits perfectly into it}else{    // number is odd because 2 DOES NOT fit perfectly into it}

Some more examples:
8 % 3 = 2
4 % 1 = 0
12 % 5 = 2

##### Share on other sites
As stated already the % operator or modulus operator calculates and returns the remainder of the division.
So for example:
if 1/2 = 0 with a remainder of 1 then 1%2 = 1
if 2/2 = 1 with a remainder of 0, then 2%2 = 0
if 3/2 = 1 with a remainder of 1, then 3%2 = 1
if 4/2 = 2 with a remainder of 0, then 4%2 = 0
if 5/2 = 2 with a remainder of 1, then 5%2 = 1

Notice the alternating pattern of 1s, and 0s in this case when we divide by a value of 2.
You can use this method to obtain numbers that are even or odd.

This loop would display the values that are even and odd from 1 though 10.

for( int i = 1; i <=10; ++i )
{
if( i%2 )
cout i << " is an odd number." << endl;
else
cout i << " is an even number." << endl;
}

##### Share on other sites
also rereading your original post it seems like you're gonna need to make a do-while loop to prompt the user for values.

##### Share on other sites
The reason you are having trouble with setw is because it's part of iomanip, so in order for your code to compile you will need to add #include<iomanip> to the top of your file.

It basically tells the stream to output the next piece of data with a set width you provide to the setw function. It will output that many characters worth of width regardless of whether or not the data fills it all up. If it doesn't, it will output blank space to fill in the rest. You can also align the output left or right, say...

cout << setw( 5 ) << right << someInt;
// will output value in someInt to the console with width of 5, right aligned

(right and left are members of std, so you either need to use the namespace std or type the fully resolved std::right, std::left)

##### Share on other sites
Quote:
 Original post by SilentEchoThe reason you are having trouble with setw is because it's part of iomanip, so in order for your code to compile you will need to add #include to the top of your file.It basically tells the stream to output the next piece of data with a set width you provide to the setw function. It will output that many characters worth of width regardless of whether or not the data fills it all up. If it doesn't, it will output blank space to fill in the rest. You can also align the output left or right, say...cout << setw( 5 ) << right << someInt;// will output value in someInt to the console with width of 5, right aligned(right and left are members of std, so you either need to use the namespace std or type the fully resolved std::right, std::left)

Thanks

##### Share on other sites
Quote:
 Original post by Haptic% returns the 'remainder' of a division.So for example, if you divide 11 by 2:2 goes into 11 five whole times - with 1 remainder.So 11%2 will return 1.*** Source Snippet Removed ***Some more examples:8 % 3 = 24 % 1 = 012 % 5 = 2

Thanks for that, but I have no idea where to start in putting it into my code. I've tried
    if (counter%2 == 1)    remainder = odd;    if (counter%2 == 0)    remainder = even;

(after putting remainder, odd, and even as int variables) and
cout << setw(odd) << odd << endl;

after the counter--;. Not sure if I'm starting out right with this..

##### Share on other sites
Quote:
 Original post by UltimatepuffI have no idea where to start in putting it into my code.

Haven't followed the entire thread, but I assume this is about problem 2:
Quote:
 Output all odd numbers between firstNum and secondNum.

You already know how to find out whether a number is odd or even. There are more ways to do it, but the suggested manner should do fine.

We start the loop with the highest number. First, let's find out if this number is odd or even:
if (secondNum % 2 == 1) remainder = odd;else remainder = even; // we don't need to test again: if it's not odd, it has to be even.

Let's see some examples of what the output should look like in several cases:

firstNum = 10 secondNum = 21output: 11, 13, 15, 17, 19firstNum = 11secondNum = 28output: 13, 15, 17, 19, 21, 23, 25, 27firstNum = 7secondNum = 16output: 9, 11, 13, 15

As you may notice, we can start our counter at either secondNum - 1 if the number is even, or secondNum - 2 if the number is odd. Let's use that in our code:

if (secondNum % 2 == 1) counter = secondNum - 2; // odd;else counter = secondNum - 1; // even

Again, as you can see in the example outputs, the only thing left to do is to decrease this counter by 2 every iteration, until it is equal or smaller to firstNum. There's no need to keep checking for the odd/even property, because if say, a number is odd then every time you add or substract a multiple of 2, you get a new number that is also odd. Same goes for even numers. The codez:

while (counter >= firstNum){  cout << counter << "\n";  counter -= 2;}

##### Share on other sites
Quote:
Original post by WanMaster
Quote:
 Original post by UltimatepuffI have no idea where to start in putting it into my code.

Haven't followed the entire thread, but I assume this is about problem 2:
Quote:
 Output all odd numbers between firstNum and secondNum.

You already know how to find out whether a number is odd or even. There are more ways to do it, but the suggested manner should do fine.

We start the loop with the highest number. First, let's find out if this number is odd or even:
if (secondNum % 2 == 1) remainder = odd;else remainder = even; // we don't need to test again: if it's not odd, it has to be even.

Let's see some examples of what the output should look like in several cases:

firstNum = 10 secondNum = 21output: 11, 13, 15, 17, 19firstNum = 11secondNum = 28output: 13, 15, 17, 19, 21, 23, 25, 27firstNum = 7secondNum = 16output: 9, 11, 13, 15

As you may notice, we can start our counter at either secondNum - 1 if the number is even, or secondNum - 2 if the number is odd. Let's use that in our code:

if (secondNum % 2 == 1) counter = secondNum - 2; // odd;else counter = secondNum - 1; // even

Again, as you can see in the example outputs, the only thing left to do is to decrease this counter by 2 every iteration, until it is equal or smaller to firstNum. There's no need to keep checking for the odd/even property, because if say, a number is odd then every time you add or substract a multiple of 2, you get a new number that is also odd. Same goes for even numers. The codez:

while (counter >= firstNum){  cout << counter << "\n";  counter -= 2;}

Wow, thanks! This really helped. Now off to work on step 3..

##### Share on other sites
Well I've managed to do all the parts except for part 3.. how would I go about doing it? I've added the variables counterR (for even numbers, don't know if I had to do that but I did) and sum (for the sum). I'm not sure what to put inside the while statement though..

##### Share on other sites
Quote:
 Original post by UltimatepuffWell I've managed to do all the parts except for part 3.. how would I go about doing it? I've added the variables counterR (for even numbers, don't know if I had to do that but I did) and sum (for the sum). I'm not sure what to put inside the while statement though..

I assume by now you are able to create a while loop that prints all the even numbers instead of odd numbers, right? Good. [smile]

So the only thing left to do, is to add them all up and print the final sum. All the even numbers are already available to you in that loop (you're already able to print them after all). So what we need is a variable outside the scope of the while loop that can keep track of the sum. Looking at your code, I guess that's where the variable named betweenNum is for, but you could also declare a new one.

Before the entering the loop, this variable should hold the value zero, because before we have started adding up the even numbers, the sum would be zero. Imagine a situation where the input would be 18 and 20: in this case there isn't a single even number between them, and therefor the sum should be zero (or non-existent, or undefined, or what ever you want to called it). So it's consistent. As a side node, it's good to always initialize you variables to 'something', because otherwise it's probably going to hold some unpredictable garbage.

Now all we have to do is use this variable to add up our even numbers. We can just add every number to it we encounter in our loop and that should give us the sum. After we exit the loop, we can print its value.

##### Share on other sites
This problem is actually very similar to the problem WanMaster helped you with, except in this case it involves even numbers and instead of printing the numbers, you must get the sum of them all.

I would have simply summed all of the even numbers and printed the odd numbers in the same loop, however, because of the way the program is structured so far, and because it is a project that demonstrates the use of loops, you can just use another loop for this problem. That way, you can use the same counter variable as well.

In this case, you must make sure sum = 0 at the very beginning of your code (otherwise it is an uninitialized variable).

Actually, a simple way to do it is to do the exact opposite of WanMaster's code (so that it makes sure the numbers are even, not odd).

if (secondNum % 2 == 1)
counter = secondNum - 1; // odd, but we want even
else
counter = secondNum - 2; // even

So let's take a few numbers for example:

15: Since the remainder of 15/2 is 1 (15 % 2 == 1), counter will begin at 15 - 1 which is 14, an even number.

14: Since the remainder of 14/2 is 0 (14 % 2 == 0), counter will begin at 14 - 2 which is 12, again an even number.

Next, you can go about it the same way as the other problem. By looping through and decrementing the counter variable by 2, until it is >= to firstNum. The only difference in this case is that with each loop you want to add the counter to sum.

sum = 0; while (counter >= firstNum){  sum += counter;  counter -= 2;}

See, it is very similar to the code for the other problem, with some small differences. Once that is done, all you do is display the sum.

I hope that helped!

##### Share on other sites
Quote:
Original post by WanMaster
Quote:
 Original post by UltimatepuffWell I've managed to do all the parts except for part 3.. how would I go about doing it? I've added the variables counterR (for even numbers, don't know if I had to do that but I did) and sum (for the sum). I'm not sure what to put inside the while statement though..

I assume by now you are able to create a while loop that prints all the even numbers instead of odd numbers, right? Good. [smile]

So the only thing left to do, is to add them all up and print the final sum. All the even numbers are already available to you in that loop (you're already able to print them after all). So what we need is a variable outside the scope of the while loop that can keep track of the sum. Looking at your code, I guess that's where the variable named betweenNum is for, but you could also declare a new one.

Before the entering the loop, this variable should hold the value zero, because before we have started adding up the even numbers, the sum would be zero. Imagine a situation where the input would be 18 and 20: in this case there isn't a single even number between them, and therefor the sum should be zero (or non-existent, or undefined, or what ever you want to called it). So it's consistent. As a side node, it's good to always initialize you variables to 'something', because otherwise it's probably going to hold some unpredictable garbage.

Now all we have to do is use this variable to add up our even numbers. We can just add every number to it we encounter in our loop and that should give us the sum. After we exit the loop, we can print its value.

So if I add the code
while(counterR >= firstNum)                 {                               cout << (sum+=counterR) << " ";                                 counterR -= 2;                 }

(sum being the 'new variable'), is this what I would have to do after initializing the sum as 0? Probably not seeing as it doesn't work well for me..

##### Share on other sites
Quote:
 Original post by deathknight2005This problem is actually very similar to the problem WanMaster helped you with, except in this case it involves even numbers and instead of printing the numbers, you must get the sum of them all. I would have simply summed all of the even numbers and printed the odd numbers in the same loop, however, because of the way the program is structured so far, and because it is a project that demonstrates the use of loops, you can just use another loop for this problem. That way, you can use the same counter variable as well.In this case, you must make sure sum = 0 at the very beginning of your code (otherwise it is an uninitialized variable). Actually, a simple way to do it is to do the exact opposite of WanMaster's code (so that it makes sure the numbers are even, not odd). if (secondNum % 2 == 1) counter = secondNum - 1; // odd, but we want evenelse counter = secondNum - 2; // evenSo let's take a few numbers for example:15: Since the remainder of 15/2 is 1 (15 % 2 == 1), counter will begin at 15 - 1 which is 14, an even number.14: Since the remainder of 14/2 is 0 (14 % 2 == 0), counter will begin at 14 - 2 which is 12, again an even number.Next, you can go about it the same way as the other problem. By looping through and decrementing the counter variable by 2, until it is >= to firstNum. The only difference in this case is that with each loop you want to add the counter to sum. *** Source Snippet Removed ***See, it is very similar to the code for the other problem, with some small differences. Once that is done, all you do is display the sum. I hope that helped!

[s]Thanks, but I've tried that and when I compile and run it, it would just output the even numbers with a little sum added to them[/s]

I started playing around a little with this and it worked! Thanks

[Edited by - Ultimatepuff on July 21, 2009 3:21:48 PM]

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628372
• Total Posts
2982305

• 10
• 9
• 13
• 24
• 11