473,327 Members | 2,112 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,327 software developers and data experts.

Looping this

Hi there, im in need to use a loop, im not sure exactly how to do it :S

########################
/*
* File: Payroll.c
* Program to calculate the wage of a user
*/
#include <stdio.h>

int main(int argc, char* argv[])
{
double hoursWorked = 0.00;
double hourlyRate = 0.00;
double pay = 0.00;
double totalAmount = 0.00;
int fieldCount = 0;

printf("Please enter hours worked: ");
fflush(stdout);
fieldCount = scanf("%lf", &hoursWorked);

if (fieldCount != 1)
{
printf("Please enter a number value.\n");
return 0;
}

while( hoursWorked < 0.0 )
{
return 0;
printf("The hours worked are %.2f\n", hoursWorked);
}

printf("Please enter hourly rate: ");
fflush(stdout);
scanf("%lf", &hourlyRate);
printf("The hourly rate is %.2f\n", hourlyRate);

printf("The total amount is %.2f\n", hoursWorked * hourlyRate);

return 0;
}
###########################
I know that theres no need to use a while loop, but i wanted to try
something

Ive got it so that if they dont enter a value, i.e 5, 3 and enter say
hello, then it says "please enter a number value"
but in that case, i want it to then return to "please enter hours worked"

ive tried a few things, none seemed to work

I tried extending the if statement:
if (fieldCount != 1)
{
printf("Please enter a number value.\n");
return 0;
}
else
{
printf("Please enter hours worked: ");
}

but then that just messed up the code :S

Help or advise would be apreciated
Nov 13 '05 #1
4 2024
={ Advocated }= wrote:
Hi there, im in need to use a loop, im not sure exactly how to do it :S

########################
/*
* File: Payroll.c
* Program to calculate the wage of a user
*/
#include <stdio.h>

int main(int argc, char* argv[])
{
double hoursWorked = 0.00;
double hourlyRate = 0.00;
double pay = 0.00;
double totalAmount = 0.00;
int fieldCount = 0;
This code looks strangely familiar.

printf("Please enter hours worked: ");
fflush(stdout);
fieldCount = scanf("%lf", &hoursWorked);

if (fieldCount != 1)
{
printf("Please enter a number value.\n");
return 0;
That quits from main(), which isn't what you want.
You want something like:

while(fieldCount != 1)
{
printf("Please enter hours worked: ");
fflush(stdout);
fieldCount = scanf("%lf", &hoursWorked);
if(fieldCount != 1)
{
printf("Error in input.\n");
}
}

This will keep looping until they give you a decent number.
}

while( hoursWorked < 0.0 )
{
return 0;
printf("The hours worked are %.2f\n", hoursWorked);


If you've returned from main(), you've ended the program (modulo a nit or
two which needn't concern us here). I explained this to you before, in
Undernet.

The printf, coming as it does after the end of the program, will simply not
happen.

--
Richard Heathfield : bi****@eton.powernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton
Nov 13 '05 #2
On Sat, 25 Oct 2003 17:57:03 +0100, ={ Advocated }= wrote:
Hi there, im in need to use a loop, im not sure exactly how to do it

I know that theres no need to use a while loop, but i wanted to try
something

Ive got it so that if they dont enter a value, i.e 5, 3 and enter say
hello, then it says "please enter a number value"
but in that case, i want it to then return to "please enter hours worked"
Let's look at the code:
printf("Please enter hours worked: ");
fflush(stdout);
fieldCount = scanf("%lf", &hoursWorked);

if (fieldCount != 1)
{
printf("Please enter a number value.\n");
return 0; ^^^^^^^^ }


Look what you are doing. If the user enters something other than
a number, the program exits! The keyword 'return' means "leave
this function now". Since the function in question is main(),
the program exits. So the first thing to do is get rid of the
return statement:

/* Point A */
printf("Please enter hours worked: ");
fflush(stdout);
fieldCount = scanf("%lf", &hoursWorked);

if (fieldCount != 1)
{
printf("Please enter a number value.\n");
/* Point B */
}

Now just consider this small piece of code. What you want to
do is go from Point B to Point A, right? We can move in the
right direction by adding a while loop around this whole
piece of code. For now, we won't worry about ending the loop:

int loop_some_more = 1;

while (loop_some_more)
{
/* Point A */
printf("Please enter hours worked: ");
fflush(stdout);
fieldCount = scanf("%lf", &hoursWorked);

if (fieldCount != 1)
{
printf("Please enter a number value.\n");
/* Point B */
}
}

Try compiling your program with these changes. You'll see
that no matter what you type in, you'll be prompted to
enter hours worked again. If you type a number, you'll
just get another prompt. If you type a non-number, you'll
be asked to enter a number value and then you'll get another
prompt.

This infinite loop can be broken by assigning zero to the
loop_some_more variable somewhere inside the loop. You just
need to figure out where the right place to do it is. (You
might need to change the code inside the loop a little
bit.) Try that yourself and post your code again if you can't
figure it out.

-Sheldon

Nov 13 '05 #3
On Sat, 25 Oct 2003 17:57:03 +0100, "={ Advocated }="
<Ha************@memail.com> wrote:
Hi there, im in need to use a loop, im not sure exactly how to do it :S
Read the comments at the bottom, then come back and look at the code.

########################
/*
* File: Payroll.c
* Program to calculate the wage of a user
*/
#include <stdio.h>

int main(int argc, char* argv[])
{
double hoursWorked = 0.00;
double hourlyRate = 0.00;
double pay = 0.00;
double totalAmount = 0.00;
int fieldCount = 0;
You never use the initial values.

Obviously, you want to start your loop here so that, if it repeats,
this prompt will be reissued.
do { printf("Please enter hours worked: ");
fflush(stdout);
fieldCount = scanf("%lf", &hoursWorked);
Since you are interested in validating the input, scanf is not your
best choice. Consider some possible inputs
1 - enter
2 - 1
3 - 1.1
4 - 1.1.1
5 - 1a
6 - 1 a
7 - a

scanf will let you catch 1 and 7. It will appear to work for 2-6 but
in cases 4-6 it will leave garbage in the input queue that may screw
up your next input.

A better approach is to read the input into a string with fgets() and
then use strtod() to both convert the data from character to double
and notify you of potential errors.

However, for this code, let's just stick to getting the loop to work.

if (fieldCount != 1)
{
At this point, scanf said there was no double. Case 1 or 7 could be
the cause.
printf("Please enter a number value.\n");
I would suggest text like "Please retry with a numeric value.\n"
return 0;
This completely exits your function and prevents you from doing
anything more. Delete it.
}
This is where your test for negative input belongs
else if (hoursWorked <= 0.) { /* we know fieldCount is 1 */
printf("Please retry with a positive value.\n");

At this point, we have finished with the value and fieldCount
indicates success or not. What you don't know is if scanf left any
junk in the queue. The safe thing to do is remove any if it did, with
something like
while (getchar() != '\n')
;

We are now done with all the input for hours worked and it is time to
close the loop
} while (fieldCount != 1 || hoursWorked <= 0.0);

This will repeat the loop if scanf did not find a number or if the
number was not positive.

while( hoursWorked < 0.0 )
This validation code belongs inside the input loop.
{
return 0;
Nothing else in this block can execute after this statement.
printf("The hours worked are %.2f\n", hoursWorked);
You want to print this out if the value is positive, not negative.
}

You create another loop here that looks exactly the same as the first.
printf("Please enter hourly rate: ");
fflush(stdout);
scanf("%lf", &hourlyRate);
After the hourly rate loop, you should print out all three lines here.
printf("The hourly rate is %.2f\n", hourlyRate);

printf("The total amount is %.2f\n", hoursWorked * hourlyRate);

return 0;
}
###########################
I know that theres no need to use a while loop, but i wanted to try
something

Ive got it so that if they dont enter a value, i.e 5, 3 and enter say
hello, then it says "please enter a number value"
but in that case, i want it to then return to "please enter hours worked"

ive tried a few things, none seemed to work

I tried extending the if statement:
if (fieldCount != 1)
{
printf("Please enter a number value.\n");
return 0;
}
else
{
printf("Please enter hours worked: ");
}

but then that just messed up the code :S

Help or advise would be apreciated

Design before you code. Once you have a design that flows the way you
want it, then you can code it.

You want a loop that you will always execute at least once but may
repeat if you don't like what happens on the current iteration. Of
all the looping constructs in C, do{}while seems to be the best
suited. Something like
do
prompt for input
obtain input
if input not valid
issue rebuke
while (input not valid)
<<Remove the del for email>>
Nov 13 '05 #4
Barry Schwarz wrote:
On Sat, 25 Oct 2003 17:57:03 +0100, "={ Advocated }="
<Ha************@memail.com> wrote:
double hoursWorked = 0.00;
double hourlyRate = 0.00;
double pay = 0.00;
double totalAmount = 0.00;
int fieldCount = 0;


You never use the initial values.


That isn't necessarily a Bad Thing.

I make a point of assigning a value to every object in my code, irrespective
of whether that value is used, simply to give the program no excuse (in
that regard, at least) for indeterministic behaviour. I know that some
people in this newsgroup think that to do so is silly, but the practice has
saved me considerable debugging time in the past, so I'm not about to
change it now.

(No, the OP didn't get this idea off me, at least not as far as I know.)
fieldCount = scanf("%lf", &hoursWorked);


Since you are interested in validating the input, scanf is not your
best choice.


<grin> Beautifully put.

--
Richard Heathfield : bi****@eton.powernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton
Nov 13 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

45
by: Trevor Best | last post by:
I did a test once using a looping variable, first dimmed as Integer, then as Long. I found the Integer was quicker at looping. I knew this to be true back in the 16 bit days where the CPU's (80286)...
5
by: masood.iqbal | last post by:
My simplistic mind tells me that having local variables within looping constructs is a bad idea. The reason is that these variables are created during the beginning of an iteration and deleted at...
1
by: Diva | last post by:
Hi, I have a data grid in my application. It has 20 rows and I have set the page size as 5. I have a Submit button on my form and when I click on Submit, I need to loop through the rows in the...
5
by: johnb41 | last post by:
I need to loop through a bunch of textbox controls on my form. The order of the loop is very important. For example, the top one must be read first, then the one below it, etc. My first...
2
by: John Dalberg | last post by:
In a traditional for loop, one can use the index (say i) and continue looping in another function and come back to original for loop (even though it's not good practice) Can the newer foreach...
5
by: Jeff | last post by:
Hey gang. I have a script that gets stats from a mssql db, and then inserts those stats into a temp table. where i can work with them as i wish. the problem is it isn't looping through all the...
0
by: anthon | last post by:
Hi all - first post! anywho; I need to create a function for speeding up and down a looping clip. imagine a rotating object, triggered by an action, and slowly decreasing in speed, till it...
4
by: XpatienceX | last post by:
Hi, Can someone help me with this assignment, I am confused of what is needed to be done here. I am suposed to design a program that models a worm's behavior in the following scenario: A...
20
by: Ifoel | last post by:
Hi all, Sorry im beginer in vb. I want making programm looping character or number. Just say i have numbers from 100 to 10000. just sample: Private Sub Timer1_Timer() if check1.value= 1...
2
by: Davaa | last post by:
Dear all, I am a student making a MS Form application in C++. I would ask a question about "Timer". Sample code which I am developing is below. private: System::Void...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.