# It's that time again!! Chapter exercises! Loops, Yippee!!

Discussion in 'Mac Programming' started by cybrscot, Feb 7, 2011.

1. ### cybrscot macrumors 6502

Joined:
Dec 7, 2010
Location:
Somewhere in Southeast Asia
#1
Okay, below I will copy my problem from the book, and my "pseudo code" then I had another idea on how to write the code, so I have a second "pseudo code" example. Are either on the right track? Which should I further develop if any? First time writing a loop, so wasn't really sure where to start.

Code:
```//I'm trying to think about how to begin writng this program, so I want to put my
//ideas on paper, (like pseudo code, because I don't really know how to do that-
//but this is my first attempt at some kind of pseudo code)
//Since this chapter taught loops, while, do and for, I'm sure this exercise will need
//a loop, but how do I know which one works best?

//pseudo code for exercise 1 chapter 6

//exercise........
//Write a program that finds the largest in a series of numbers
//entered by the user.  The program must prompt the user to enter numbers
//one by one.  When the user enters 0 or a negative number, the program must
//display the largest nonnegative number entered.  The numbers musn't necessarily
//be integers.

//Is the below anywhere close?  I'm curious to know how the user can continue to store
//new numbers in &user_number, wouldn't each new number entered overwrite the previously
//entered number?  Or will the numbers somehow be kept seperated in user_number? I'm thinking
//that each new user entry of a number needs to be user_number1, user_number2, etc. etc.
//But since this is a loop, it's going to keep using the same printf, scanf.

// Known problem... I have no idea how to tell the computer to print the largest number of
// user input.  When it comes time for the printf to print the largest number, how
// do I distiguish the largest number from just any number?  I thought about telling
// the computer to print the number with the most character spaces used, but that
// won't work as .0000001 is obviously not bigger than 1.  Hmmmm...?

//I hope somebody will give me good news!!

float user_number ;

for ( ; user_number > 0 ; ) {                  // for and expression
printf (enter a number:) ;                       // loop body
scanf (accepts user number %f, &user_number)    //loop body

if (user number <= 0) break ;                  // loop body with breakout
}

printf ("The largest nonnegative number you entered is: %f, user_number) ;

return 0 ;

}

//Or my second idea just kicked in.......
//I need the printf and scanf to be in a loop that repeats until 0 or a negative
//number is entered, so I need to run the loop before the variable is tested. So
//maybe I need a "do" loop instead?  Do (statement) While (expression) statement
// I'm sure there's something wrong here too, because I don't yet know how, but am I
//on the right track?  I don't feel like my while is in the loop? Do I need to extend
//the brackets and include while? If so, where do I break out?

do {
scanf (&f, user_number) ;
}
while (user_number > 0) ;
if (user_number <= 0)
printf(The largest number you entered was) ;

return 0 ;
```

### Staff Member

Joined:
Aug 16, 2005
Location:
New England
#2
The second is pointing in the right direction.

Try it and make sure it will let you handle the input part, several positive numbers until a zero or negative number is input.

Here's a hint for the input storage problem. You don't need to store all the numbers, all you need to store is the current high water mark (maximum).

B

3. ### lee1210 macrumors 68040

Joined:
Jan 10, 2005
Location:
Dallas, TX
#3
I didn't look at your code or pseudocode at all, but based on your comment about needing to store each entered number in separate variables...
you haven't gotten to arrays (I think) so that is not an option... however, if you're trying to find the maximum number, how many pieces of data do you really need to store? It doesn't seem like you need a whole history of numbers entered, you just need to keep track of some information. What do you need to keep track of? How many values do you need to store to do that?

-Lee

Edit: Just saw balmw's post and the "second idea" you had. That sounds like the right track. do...while(onlyPositives) or do...while(!done), etc. Honestly, I rarely if ever use do...while, just while and initialize the control variable to ensure at least one execution. There are some rare instances where this isn't possible and a do is needed, but i can't think of the last time i used one. You might also want to consider tracking if they entered at least one positive in some manner, so you can say that there is no maximum since no numbers were entered. Otherwise you'll just say some uninitialized value or whatever you start with (say, -1) is the maximum, which would be a lie.

4. ### subsonix macrumors 68040

Joined:
Feb 2, 2008
#4
The do/while loop seems like the most sensible approach to me, since you don't need to increment a variable, and you can also skip break.

There is one more thing you will need, and that is to remember the highest number inside the loop.

First initialize the memory variable to zero before the loop, then inside, compare it to the entered number, if the entered number is higher, let memory = entered.

### Staff Member

Joined:
Aug 16, 2005
Location:
New England
#5
I encourage you to separate the problem out. Deal with the input, loop and exit conditions before you implement the maximum finder (as per subsonix's approach).

Then, as a challenge, find the minimum non-zero number and the number of numbers that were input in the same loop.

B

6. ### subsonix macrumors 68040

Joined:
Feb 2, 2008
#6
It's great for user input, if you ever use that from the terminal. Consider for example:

Code:
```do{
print "enter a four digit number"
get number
}while( number is not valid );
```
I don't see the point of advising against it, on the sole argument that it's not as common. In some instances it makes more sense, like here for example. You could really argue to not use anything else but the for loop, and simply leave the some fields empty, but why.

7. ### lee1210 macrumors 68040

Joined:
Jan 10, 2005
Location:
Dallas, TX
#7
I'm pretty sure I did not advise against it, just provided some colloquial information about my use. I'd say it's just as well to do:
Code:
```numberIsValid=0;
while(!numberIsValid) {
...
}
```
I also said there were situations where "do" is needed. In any event, they all do the same thing. Ultimately a condition gets tested and the loop continues or it doesn't. "For" provides some conveniences for initialization and incrementation/modification of control variables, but you can do this yourself.

-Lee

8. ### cybrscot thread starter macrumors 6502

Joined:
Dec 7, 2010
Location:
Somewhere in Southeast Asia
#8
Thanks team! ( I would say "guys", but I don't know if everybody here is a guy, but I'm assuming Lee is! (name)

Balamw, as a challenge, huh? LOL All this stuff is a challenge for me at this level! Building code is like a combination between an old school "word problem" from Algebra days and a puzzle. The problem really is just a "word problem", and seems easiest for me to think of it that way to sort it out and what I need to do. Then once I do that, I've got to setup the proper equations (we call expressions) then once I do that, I've got to execute it all in the correct order. Challenging, but i can do it!! Thanks, I'm glad example #2 is on the right track. I read in the book that the "for" loop is the most useful and flexible generally and most popular, so I just figured I would try to use it first, but I couldn't make it make sense. There's probably a way, but I couldn't figure it out. The "do" is actually the most obvious, because I'm clearly running the loop body before I evaluate the users input.
Back to the drawing board....stay tuned!

9. ### subsonix macrumors 68040

Joined:
Feb 2, 2008
#9
Yes and you could do it with for as well of course:

Code:
```for( numberIsValid = 0; !numberIsValid; ){
...
}
```

10. ### lee1210 macrumors 68040

Joined:
Jan 10, 2005
Location:
Dallas, TX
#10
or

Code:
```labelA: printf("Enter number: ");
...
if(!numberIsValid) goto labelA;```
=)

-Lee

11. ### subsonix macrumors 68040

Joined:
Feb 2, 2008
#11
Yeah, so you see, we really need nothing else. Only goto!

12. ### lee1210 macrumors 68040

Joined:
Jan 10, 2005
Location:
Dallas, TX
#12
It's all jne or je anyway, right? =)

-Lee

13. ### subsonix macrumors 68040

Joined:
Feb 2, 2008
#13
Ha, yeah, some branch instruction.

### Staff Member

Joined:
Aug 16, 2005
Location:
New England
#14
Exactly, and setting the problem up as clearly as possible is a big part of solving it.

Divide and conquer.

The first thing you need is a "loop that repeats until 0 or a negative number is entered." (your words). Get that bit done. Then introduce the bits that process the entered numbers.

B

15. ### cybrscot thread starter macrumors 6502

Joined:
Dec 7, 2010
Location:
Somewhere in Southeast Asia
#15
Okay, here goes, got some problems/questions commented out in there. Am I any closer?

Code:
```#include <stdio.h>

main ()

{

float user_number = 0 ;  //Is this initializing the memory variable to zero?
// I think so, but since the user enters a number and
// it's immediately stored in user_number, how do I compare
// old user_number vs. new user_number, they'll be the same
// immediately after it's input by the user.?.?.?

do {
printf ("Enter a number: ") ;
scanf ("%f", &user_number) ;
//subsonix said inside the loop compare the prev stored number to the
//user entered number, do I do it here, at this point in the loop?
//like this....
//if (user_number > old user_number) then user_number != old user_number
//assumes that the old user number is the current highest humber as the very
//first number would be the highest by default
} while (user_number > 0 ) ;
// I need a stmt here to finish the do/statement/while/expression/stmt form
// but I don't know what I want it to do now. If the usernumber is > 0 then
// the loop repeats, (which is what I want).  I don't want it to print anything
// yet either. Maybe an if statement?

if (user_number <= 0 ) break ;    // can I put a break here?

printf ("The largest number you printed was: ", user_number) ;

return 0 ;

}  	```

16. ### lee1210 macrumors 68040

Joined:
Jan 10, 2005
Location:
Dallas, TX
#16
You will need one variable for input and one for the current maximum. You can initialize the current maximum to 0, -1, etc. so that any valid number entered is greater than that value. Outside of your loop you can see if the maximum is equal to the value you initialized it to, and if so print that no numbers were entered, and exit. You can't use break if you're not in a loop. You might do something like
if(max number == original max value) {
print error message
} else {
print the max value entered
}

In your loop you would compare the number entered to the current maximum, not just the previous entered value (unless the user is only allowed to enter 2 numbers.

-Lee

17. ### cybrscot thread starter macrumors 6502

Joined:
Dec 7, 2010
Location:
Somewhere in Southeast Asia
#17
That break that I have in there, you said I can't use a break if I'm not in a loop, but I thought that if stmt was part of the loop? Loop is do/statement/while/expression/statement. I thought my "if" was the statement at the end of the while/expression/my "if" here, guess not huh? But why isn't it? If not, where exactly do you see my loop ending? I don't even know!

18. ### cybrscot thread starter macrumors 6502

Joined:
Dec 7, 2010
Location:
Somewhere in Southeast Asia
#18
So I set both variables to 0. But how the heck do I get my one scanf entry into two variables? If it's stored in user_number, how do I get it to move over to current_maximum if it qualifies? I'm lost! Arghh!!!!
And if I set user_number == to current_maximum, then they will always be equal, the current_maximum will also make itself the user_number, even if it's lower, not higher.

19. ### lloyddean macrumors 6502a

Joined:
May 10, 2009
Location:
Des Moines, WA
#19
Code:
```#include <stdio.h>

int main()
{
int     valueMaxSet     = 0;

float   value, valueMax;

do
{
printf("Enter a number: ");
scanf("%f", &value) ;

if ( !valueMaxSet )     { valueMaxSet = 1; valueMax = value; }
if ( value > valueMax )  { valueMax = value; }
} while ( value > 0 ) ;

printf("The largest number you printed was: ", valueMax);

return EXIT_SUCCESS;
}
```

20. ### lee1210 macrumors 68040

Joined:
Jan 10, 2005
Location:
Dallas, TX
#20
It looks like the if is the first statement after the "while(...);", so it is not part of the loop. Your loop will end when user_number is less than or equal to 0, so that's whenever a user enters a value that's 0 or negative.

How would you normally get a value stored in a variable? There's an operator meant for that particular purpose. The second part there regarding == sounds like good old fashioned country gibberish (just kidding, I know this stuff takes a while to wrap your head around, and the nomenclature can be tough to tackle). The == evaluates to 0 or 1 based on whether the two operands are equal. It doesn't "lock" their values together, etc. Neither does the =. It copies the value of the right operand into the left operand. You will eventually learn about pointers that can sort of have the affect you're thinking of, but = does not do anything like that. It's like you have two pieces of paper, and one of them has 7 written on it. You can then say "copy the value on that piece to the other", and now both will have 7 written on them. From then on, they are not at all related. You could erase the 7 on either sheet without affecting the other.

Giving a man a fish is robbing him of a learning opportunity. Sometimes it's necessary if someone is really frustrated, but I think progress was being made.

-Lee

21. ### cybrscot thread starter macrumors 6502

Joined:
Dec 7, 2010
Location:
Somewhere in Southeast Asia
#21
Ahhh, I haven't had a chance to read your replies yet as I was in bed, but I just jumped out because I think I clarified my logic/thought process on this user_number/current_maximum thing. Maybe is this closer..... Just look at this from my thought process, not as code of course. That'll be tomorrows mission.

Code:
```float user_number, maximum_number = 0

the scanf will accept the user_number scanf("%f", &user_number)

then, I will campare the user_number against the maximum_number

like, if (user_number > maximum_number) store into maximum_number
maximum_number = user_number (in other words, assign user number to maximum number)

Say the user entered 4.

then it would be  if ( 4 > 0) which it is, then 4 gets stored into the maximum_number
maximum_number = 4

```

22. ### lee1210 macrumors 68040

Joined:
Jan 10, 2005
Location:
Dallas, TX
#22
Ding, ding, ding!

-Lee

Joined:
Feb 2, 2008
#23

### Staff Member

Joined:
Aug 16, 2005
Location:
New England
#24
Or even negative as lee1210 suggested.

However the technique of using a variable as a flag is a useful one that doesn't hurt to introduce to cybrscot.

As I suggested you might actually try to keep track of how many positive numbers were entered (e.g. if you were going to get the arithmetic mean of the numbers), and having to figure out how to adapt this for minimum instead of maximum may also be interesting.

B

25. ### subsonix macrumors 68040

Joined:
Feb 2, 2008
#25
Yes, it can be useful, finite-state machines and else where. I was merely thinking of the bare minimum to fulfill the requirements here for simplicity's sake. But I agree that it's a good suggestion to expand on the exercise and introduce calculations of min/max mean and so on.