473,322 Members | 1,562 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,322 software developers and data experts.

Convert a while loop to a for loop

Hi!

I need to convert the following while loop:
count = 1;
while (caloriesForItem != 0, count != numberOfItems )
{
cout<<"Enter the calories: ";
cin >> caloriesForItem;
totalCalories += caloriesForItem;
count++;
}

This is what I have come up with:
totalCalories += caloriesForItem;
for (count = 1; caloriesForItem != 0; count != numberOfItems)
{
cout<<"Enter the calories: ";
cin >> caloriesForItem;
count++;
cout << "Total calories eaten today = " << totalCalories << endl;
}

However the output is not the same?

any pointers perhaps?
Mar 25 '12 #1
6 8165
YarrOfDoom
1,247 Expert 1GB
First of all, in the condition for that while-loop, you're using the comma wrong:
The C++ Specification section 5.18, page 92
A pair of expressions separated by a comma is evaluated left-to-right and the value of the left expression is
discarded
. The lvalue-to-rvalue (4.1), array-to-pointer (4.2), and function-to-pointer (4.3) standard conversions
are not applied to the left expression. All side effects (1.9) of the left expression, except for the
destruction of temporaries (12.2), are performed before the evaluation of the right expression. The type and
value of the result are the type and value of the right operand;
the result is an lvalue if its right operand is.

In contexts where comma is given a special meaning, [Example: in lists of arguments to functions (5.2.2)
and lists of initializers (8.5) ] the comma operator as described in clause 5 can appear only in parentheses.
[Example:
f(a, (t=3, t+2), c);
has three arguments, the second of which has the value 5. ]
So for your while-loop, only count != numberOfItems is used. You should use the logical and-operator (&&) instead of the comma-operator.

As for the for-loop, it's also a bit different from what you have. The structure for a for-loop is (also in the C++ Specification; section 6.5.3, page 99):
for(initialisation;condition;expression)
Where initialisation is executed before the loop starts, and expression is executed after each iteration (which makes it a good place to increment your counter). The loop stops when condition is false at the start of an iteration (just like a while loop).
Mar 25 '12 #2
Hey, whatever sir said is absolutely fine, but if you didnt get it from that, here is a code block :

totalCalories += caloriesForItem;
for (count = 1; caloriesForItem != 0 && count != numberOfItems; count++)
{
cout<<"Enter the calories: ";
cin >> caloriesForItem;
cout << "Total calories eaten today = " << totalCalories << endl;
}

Hope now this is clear to you!! :)
Mar 27 '12 #3
for(count=1;caloriesForitem!=0 || count!=numOfItems;count++)
{
cout<<"Enter num of cals:"<<endl;
cin>>caloriesForitem
cout<<" "<<endl;
totalCalories = totalCalories + caloriesForitem;
cout<<"Total cals eaten today="<<totalCalories<<endl;
}

//your while condition is set to terminate..
//if one of the two condition is true..
//meaning you need to put the logical OR in your for loop condition. =)
Mar 28 '12 #4
@rekedtechie :

Hey, I would totally agree with you, but dear it is required to stop if either condition fails so it has to be and operator.. I hope I have made myself clear to you.. :)
Mar 28 '12 #5
//by the way, the correct looping process is like this..

for(count=1;count<=NumOfItems;count++)
{
cout<<"enter num of cals:"<>endl;
cin>>numOfCalories;
if(numOfCalories==0)
{
goto EndOfLoop;
}
else
{
totalCalories = totalCalories + numOfCalories;
}
}
EndOfLoop:
cout<<"Total Calories eaten today: "<<totalCalories<<endl;

//wait, i will post the other looping formats..=)
Mar 28 '12 #6
please correct this part..

<>endl;

make these..

<<endl;

//maybe this note.. can help you in looping process..

//FOR LOOP
for(initialization;condition;variable inc/dec)
{
statements..
}

//WHILE LOOP
varable initialization;
while(condition)
{
statements..
variable inc/dec
}

//DO WHILE LOOP
variable initialization;
Do
{
statements..
variable inc/dec
}while(condition);


logical OR ||
logical AND &&

//these are the looping formats, and i included the commonly used logical operator..=)

condition - if the condition is true, then the looping process will continue..

for(i=0;i<=5;i++)
i=0+1
i=1
condition is true..

if i reached 5 then i++ again..
meaning i=6, then the condition will turn into false..
-terminating the looping process.

you can also do multiple loops..
prod=0;
for(cl=0;cl<=5;cl++) {
for(rw=0;rw<=5;rw++)
{
cout<<" "<<rw*cl;
//to show the results of 5 numbers in one line of results..
}
cout<<endl;
//to create another line results..
}
thats all..good luck. =)

remove this code..
prod=0;
its nothing..
//result looks like this..

0 1 2 3 4 5
0 0 0 0 0 0
1 1 2 3 4 5
2 2 4 6 8 10
3 3 6 9 12 15
4 4 8 12 16 20
5 5 10 15 20 25
Mar 28 '12 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

6
by: Sybren Stuvel | last post by:
Hi there, Is it possible to use an assignment in a while-loop? I'd like to do something like "loop while there is still something to be read, and if there is, put it in this variable". I've been...
0
by: Brent Wege | last post by:
Hey guys, kinda scratching my head on this one. Each of these insert queries takes about 1 second in QA, but when I decide to loop it 100 times instead of manually inserting it 100 times, it will...
8
by: Shamrokk | last post by:
My application has a loop that needs to run every 2 seconds or so. To acomplish this I used... "Thread.Sleep(2000);" When I run the program it runs fine. Once I press the button that starts the...
3
by: archeryguru2000 | last post by:
Hello, I've been stumped for several weeks on this particlar program. At work here, we have 30 machines that we record scrap data on. I take this data and create spreadsheets (boring) that can be...
2
by: recordlovelife | last post by:
So I am trying to display a title, date, and content of a wordpress blog. Word press provides nice drop in functions to get the job done with simple names like "the_title", and the "the_content" But...
10
by: Jason (Kusanagihk) | last post by:
To all, I have written a SerialPort class / application using C# and .Net Framework 3.0. but I have a question; since my serialPort class / application is not a Windows Form application (rather...
2
by: deggler | last post by:
hi, i'd need to run a while ($row = mysql_fetch_array($result)) loop thru the whole table and then one more time. this last time the $row variable shouldn't get any values. i just need everything...
1
by: robotlizz | last post by:
Hello - I am a brand new at Java and I am having a hard time with a program I have to turn in tomorrow. I can not get the 'Q' option to work and the loop goes on forever. I've tried to go over the...
3
by: redcodeheaven | last post by:
Hello my teacher gave me an exercise to enter my name and 2 numbers the output must show the sum and the product of these 2 numbers and keep repeating the same procedure using a while loop till i...
1
by: Jose Luis Barrio | last post by:
I have an application that has a textbox and 3 buttons. With the first button I generate a random code and is showed in the textbox. The second button generates codes automatically and I want to use...
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...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
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: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
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
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.