Re: C program question
From: Barry Schwarz (schwarzb_at_deloz.net)
Date: 10/31/04
- Previous message: Barry Schwarz: "Re: A loop with C struct"
- In reply to: oasf2004_at_yahoo.com: "C program question"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Sat, 30 Oct 2004 17:05:47 -0700
On 30 Oct 2004 13:57:47 -0700, oasf2004@yahoo.com wrote:
>Hi All,
>
>One of the exercises of my C book ("C by Dissection" by Kelley and
>Pohl) asked me to write a program that reads in an integer value for n
>and then sums the integers from n to 2 * n if n is nonnegative, or
>from 2 * n to n if n is negative. I think I was able to wrote
>successfully the first part of the exercise, but I couldn't write the
>second part. Please, see bellow the first part of my code:
>
>#include <stdio.h>
>
>int main()
>{
> int n;
>
> printf("Input one integer: ");
> scanf("%d", &n);
> while (n >= 0)
> printf("The result is %d\n", n += (2 * n));
This does not sum the integers from n to 2*n. It only calculates and
prints 3*n.
If the user inputs 4, the desired answer is 30 (4+5+6+7+8) while your
code prints 12 (4+8).
While there is a formula for the sum of integers from n to 2*n, I am
pretty sure the object of the exercise is to generate a loop that
computes the desired value.
>
> return 0;
>}
>
>How could I write the second part of my code? I have no idea how could
>I write a second while loop in order to get the sums from 2 * n to n,
>if n is negative. I have tried:
>...
>while (n < 0) {
> printf("The result is %d\n", n -= (2 * n));
>....
>but of course I didn't get the correct answer.
>Thanks in advance for any hint!
>Hoffmann
Once you have the loop for positive values, the corresponding loop for
negative ones should be easy.
<<Remove the del for email>>
- Previous message: Barry Schwarz: "Re: A loop with C struct"
- In reply to: oasf2004_at_yahoo.com: "C program question"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|