If I need to add up all integers in a line (they're separated by space)
How can I do that??
e.g.
input : 1 4 5 2 3
sum : 15
input : 2 3
sum: 5
Nov 14 '05
22 4034
Ben Pfaff wrote: CBFalconer <cb********@yah oo.com> writes:
Obviously the first control structure that came to your mind was a for loop. To me, I would start with a while loop, as below.
while (EOF != (c = getchar())) { }
and only then would I expand the loop...
As a stylistic issue, I just don't like to combine assignments and tests. I can understand it just fine, of course, but I usually avoid doing it in my own code. That's the only reason I use `for' instead of `while' in that code.
You chose an infinite loop, with a test to break out of it. This
doesn't emphasize the exit condition, as opposed to a loop which
describes the exit point. It doesn't have to have an embedded
assignment. Remember, I am not criticizing, I am just
investigating the thought processes involved.
c = getchar();
while (EOF != c) {
....
c = getchar();
}
--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
CBFalconer <cb********@yah oo.com> writes: Ben Pfaff wrote: CBFalconer <cb********@yah oo.com> writes:
Obviously the first control structure that came to your mind was a for loop. To me, I would start with a while loop, as below.
while (EOF != (c = getchar())) { }
and only then would I expand the loop...
As a stylistic issue, I just don't like to combine assignments and tests. I can understand it just fine, of course, but I usually avoid doing it in my own code. That's the only reason I use `for' instead of `while' in that code.
You chose an infinite loop, with a test to break out of it. This doesn't emphasize the exit condition, as opposed to a loop which describes the exit point. It doesn't have to have an embedded assignment. Remember, I am not criticizing, I am just investigating the thought processes involved.
There are pros and cons to each approach. I can read and write
code in either style. I try to conform to the existing style
when I contribute to projects.
I tend to write most of my code for GNU projects; the GNU coding
standards discourage assignments in `if' conditions, and I've
always mentally extended that to looping constructs. Over the
last few years I've begun to realize why it's not really the same
situation, but the habit is ingrained.
On the other hand, when I write code at a particular company
founded by my PhD advisor, I would use a `while' loop with an
assignment, because that coding style is common there. There, I
would write the program something like this:
/*
* sumStdin.c
*
* Brief description:
* Sums integers from stdin and prints the sum to stdout.
*
* Copyright (C) 2005 BigCorp Subsidiary, Inc.
*/
#include <stdio.h>
#include <ctype.h>
/*
* main()
*
* Description:
* Reads integers from stdin and prints their sum on stdout.
*
* Return value:
* Always returns 0.
*
* Side effects:
* I/O.
*/
int
main(void)
{
unsigned total = 0, current = 0;
int c;
while ((c = getchar()) != EOF) {
if (isdigit(c)) {
current = current * 10 + (c - '0');
} else {
total += current;
current = 0;
}
}
printf("%u\n", total + current);
return 0;
}
--
int main(void){char p[]="ABCDEFGHIJKLM NOPQRSTUVWXYZab cdefghijklmnopq rstuvwxyz.\
\n",*q="kl BIcNBFr.NKEzjwC IxNJC";int i=sizeof p/2;char *strchr();int putchar(\
);while(*q){i+= strchr(p,*q++)-p;if(i>=(int)si zeof p)i-=sizeof p-1;putchar(p[i]\
);}return 0;}
On Fri, 28 Jan 2005 23:25:34 GMT, CBFalconer
<cb********@yah oo.com> wrote: Obviously neither is wrong, but why is there such a basic difference in the selection of code structure?
"There are nine and ninety ways / to sing the tribal ways / and every
single one of them is right!" [Kipling, from memory]
Some might use a do...while loop, or use a goto, or many other things.
In engineering there is seldom /a/ right way, there are definitely
wrong ways (anything which doesn't work is wrong, no matter how elegant)
but otherwise it is largely an aesthetic choice or a matter of taste.
De gustibus nil disputandem est...
Chris C
In article <41************ ***@yahoo.com>, cb********@yaho o.com says... This brings up a point to me. Obviously the first control structure that came to your mind was a for loop. To me, I would start with a while loop, as below.
while (EOF != (c = getchar())) { }
and only then would I expand the loop, and your code looks just fine for the purpose, into:
while (EOF != (c = getchar())) { if (isdigit (c)) current = current * 10 + (c - '0'); else { total += current; current = 0; } } printf ("%u\n", total + current); return 0;
Obviously neither is wrong, but why is there such a basic difference in the selection of code structure?
Because you are a pascal programmer at heart?
--
Randy Howard (2reply remove FOOBAR)
Randy Howard wrote: In article <41************ ***@yahoo.com>, cb********@yaho o.com says...
This brings up a point to me. Obviously the first control structure that came to your mind was a for loop. To me, I would start with a while loop, as below.
while (EOF != (c = getchar())) { }
and only then would I expand the loop, and your code looks just fine for the purpose, into:
while (EOF != (c = getchar())) { if (isdigit (c)) current = current * 10 + (c - '0'); else { total += current; current = 0; } } printf ("%u\n", total + current); return 0;
Obviously neither is wrong, but why is there such a basic difference in the selection of code structure?
Because you are a pascal programmer at heart?
There is that :-) I never saw any need for a pdecl.
--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
In article <sl************ ******@ccserver .keris.net>,
Chris Croughton <ch***@keristor .net> wrote:
.... Some might use a do...while loop, or use a goto, or many other things. In engineering there is seldom /a/ right way, there are definitely wrong ways (anything which doesn't work is wrong, no matter how elegant) but otherwise it is largely an aesthetic choice or a matter of taste. De gustibus nil disputandem est...
In the real world (outside of academia and/or newsgroups), anything that
works is "right" (this is a logical extension of "anything that doesn't
work is wrong"). Trust me. I know of what I speak.
So, I would edit what you said above to:
..., there is seldom a right way, there is usually a *best* way ga*****@yin.int eraccess.com (Kenny McCormack) wrote: In article <sl************ ******@ccserver .keris.net>, Chris Croughton <ch***@keristor .net> wrote: ...Some might use a do...while loop, or use a goto, or many other things. In engineering there is seldom /a/ right way, there are definitely wrong ways (anything which doesn't work is wrong, no matter how elegant) but otherwise it is largely an aesthetic choice or a matter of taste. De gustibus nil disputandem est...
In the real world (outside of academia and/or newsgroups), anything that works is "right" (this is a logical extension of "anything that doesn't work is wrong"). Trust me. I know of what I speak.
No, you don't. Anything that _seems_ to work may be "right" by
management standards, but from a sysadmin's POV, it's only right if it
continues to work even if you a. change the hardware, b. change the OS
version (e.g., from Win98 to WinXP), and c. stop manually fiddling
around the effects of blatant bugs.
Richard
On Thu, 14 Apr 2005 12:30:43 GMT, Kenny McCormack
<ga*****@yin.in teraccess.com> wrote: In article <sl************ ******@ccserver .keris.net>, Chris Croughton <ch***@keristor .net> wrote: ...Some might use a do...while loop, or use a goto, or many other things. In engineering there is seldom /a/ right way, there are definitely wrong ways (anything which doesn't work is wrong, no matter how elegant) but otherwise it is largely an aesthetic choice or a matter of taste. De gustibus nil disputandem est... In the real world (outside of academia and/or newsgroups), anything that works is "right" (this is a logical extension of "anything that doesn't work is wrong"). Trust me. I know of what I speak.
Not as an absolute, no, there are many places where things not adhering
to things like coding styles are 'wrong' no matter how well they work.
Including trivia like whether you use x * 2 or x >> 1 (where I work now
I've been not allowed to check in a source file because the person
inspecting it saw that I'd used the x*2 form!).
So, I would edit what you said above to:
..., there is seldom a right way, there is usually a *best* way
Not even that. Which is 'best' out of "x * 2" and "x << 1"? There may
be occasions when one is marginally more efficient or more maintainable
than the other, but very often "more maintainable" is in the eye of the
beholder and efficiency depends on the details of the environment.
There is seldom a 'right' way, there is usually some way which someone
(if you're unlucky, your boss) feels is the 'best' way with no reason
other than "I prefer it"...
Chris C
Chris Croughton wrote: On Thu, 14 Apr 2005 12:30:43 GMT, Kenny McCormack <ga*****@yin.in teraccess.com> wrote:
In article <sl************ ******@ccserver .keris.net>, Chris Croughton <ch***@keristor .net> wrote: ...
Some might use a do...while loop, or use a goto, or many other things. In engineering there is seldom /a/ right way, there are definitely wrong ways (anything which doesn't work is wrong, no matter how elegant) but otherwise it is largely an aesthetic choice or a matter of taste. De gustibus nil disputandem est...
In the real world (outside of academia and/or newsgroups), anything that works is "right" (this is a logical extension of "anything that doesn't work is wrong"). Trust me. I know of what I speak.
Not as an absolute, no, there are many places where things not adhering to things like coding styles are 'wrong' no matter how well they work. Including trivia like whether you use x * 2 or x >> 1 (where I work now I've been not allowed to check in a source file because the person inspecting it saw that I'd used the x*2 form!).
Had I been the inspector, I would also have forbidden
the use of `x * 2' as a substitute for `x >> 1' -- assuming
I was alert that day, of course.
-- Er*********@sun .com
Eric Sosman <er*********@su n.com> spoke thus: Had I been the inspector, I would also have forbidden the use of `x * 2' as a substitute for `x >> 1' -- assuming I was alert that day, of course.
You certainly seem to be alert today :-)
--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cybers pace.org | don't, I need to know. Flames welcome. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: a |
last post by:
(I've reached that familiar place where I've got a nagging little
problem in a program I'm writing but I've been staring at code for too
long and I probably wouldn't be able to recognize the answer even if I
was staring right at it.)
I'm trying to design a function that reads input from my data file into
(a pair of) arrays. Simple enough? However, each line of the file is
either going to be 4 integers or a character (then a carriage...
|
by: agent349 |
last post by:
Hi,
I'm fairly new to c++. I need user input in the form of dollar
amounts, ie: "$10.00". I'd like to remove the dollar sign "$" then
store the rest in a variable. How do I go about removing the dollar
sign? Thanks in advance!
|
by: Hulo |
last post by:
In a C program I am required to enter three numbers (integers) e.g. 256
7 5 on execution of the program.
C:\> 256 7 5
There should be spaces between the three numbers and on pressing
"enter", further processing is done. The problem requires me to check
whether three numbers have actually been entered in the input line and
to warn if less or more numbers have been entered.
|
by: moostafa |
last post by:
Hi,
I'm writing a program that performs arithmetic operations on integers.
I want to be able to type in a bunch of integers seperated by any
amount of white space then terminate input with a non-integer
character. I plan to put my input into an array, and while I have a max
size I don't have a min and don't know exactly how many arguments to
expect.
I would really appreciate any ideas.
Cheers.
|
by: sam |
last post by:
hi all,
i'm starting to put together a program to simulate the performance of
an investment portfolio in a monte carlo manner doing x thousand
iterations and extracting data from the results.
i'm still in the early stages, and am trying to code something simple
and interactive to get the percentages of the portfolio in the five
different investment categories. i thought i'd get in with the error
handling early so if someone types in...
| |
by: Kavya |
last post by:
I saw these two ways for validating input
First Way
--------------
#include <iostream>
#include <limits>
using namespace std;
int main() {
|
by: powerej |
last post by:
writing a program that asks how many numbers the users want to enter, then input an integer for the amount of numbers said, output: number of integers entered, sum of them, average of them, maximum value entered and min value entered. the min is where i am having a problem i can get everything else to print out but i am doing something wrong in my while loop can someone please help me.
import javax.swing.*; // gets option pane
...
|
by: n3o |
last post by:
Hello Comp.Lang.C Members,
I have an issue with user input that I have been trying to figure out
for the longest. For instance, let's say you have something like this:
void foo()
{
int num;
printf("Please enter a number: ");
scanf("%d", &num); // yes I know this function may throw a
|
by: manxie |
last post by:
Dear All Readers,
I'm supposed to create a program with a switch and using voids to execute number of codes, that includes finding sum, average, maximum, and minimum, please read my code:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
void WELCOME();
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |