C program question

oasf2004_at_yahoo.com
Date: 10/30/04


Date: 30 Oct 2004 13:57:47 -0700

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));
    
    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



Relevant Pages

  • Re: Struggling with K&R
    ... The exercises are impossible for me to do. ... It is easy to draw the histogram with the bars ... Now if we define a "word" as consecutive letters, ignoring awkward cases like "it's", and a non-word as anything that is not a letter, we can read the input character by character, and maintain two states. ... int main ...
    (comp.lang.c)
  • Re: Working with char
    ... In one of my exercises I have to write a program that gets a name ... If you deleted the scanf and changed first_letter to an int, ... but it is a good habit to get into. ... Remove del for email ...
    (comp.lang.c)
  • having a problem with calling a function
    ... Im trying to teach myself programming, and I am doing exercises out of the book C by Dissection by Ira Pohl. ... I am stuck on one of them and can't figure out how to fix it. ... int is_prime ...
    (comp.lang.c)
  • Re: Solutions for the Kernighan and Ritchie
    ... I've read the Kernighan and Ritchie some time ago, and then again, but ... this time I've done the full set of exercises. ... The test driver for exercise 4.2 does not test the atoffunction: ... int main ...
    (comp.lang.c)
  • Re: A very **very** basic question
    ... exercises, little things pop up that I need to understand more fully. ... Thus, below, and although this is not the exact code, the principle of ... int i = 0; ...
    (comp.lang.c)