Please help!!

This is a discussion on Please help!! within the C Programming forums, part of the General Programming Boards category; This C stuff is driving me up the wall.....can someone help me please....... Is there a way to list all ...

  1. #1
    Registered User
    Join Date
    Jun 2002
    Posts
    1

    Please help!!

    This C stuff is driving me up the wall.....can someone help me please.......

    Is there a way to list all the odd numbers when the user enters 2 integers (second number bigger than first number)

    Is there a key word that I should be listing, or a specific variable that I should declare so that it will print out only odd numbers...


    I thought about it, something like rand() to list random numbers, between a certain number......

    but what if the user enters 2 as 1st num... and 400 as 2nd number.... how does it know to only pick out the odd numbers.....

    PLEASE HELLP......I'm soooo lostttt!!!
    Kiana

  2. #2
    Registered User
    Join Date
    Sep 2001
    Location
    Australia
    Posts
    212
    I don't normally just give answers

    Code:
    #include <stdio.h>
    
    int main() {
        int low, high, count;
        printf("Enter Lower bound: ");
        scanf(" %d",&low);
        printf("Enter Upper Bound: ");
        scanf(" %d", &high);
        
        count = low;
        while (low <= high) {
            if (count %2 == 1) {
                printf("%d\n",count);
            }
        }
        return 0;
    }
    kwigibo

  3. #3
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    In this last post (sample code by kwigibo), you can substitute this
    >if (count %2 == 1) {

    for this:
    >if ( (count & 01) == 1) {

    to avoid the arithmatic being performed. It gives the same result, but is slightly more efficient (I believe!).

    Opps, just noticed your loop is infinite, you aren't changing the value of the loop control variables. A better version might be:

    Code:
    #include <stdio.h>
    
    int main(void) 
    {
        int low, high;
        
        printf("Enter Lower bound: ");
        if (scanf(" %d",&low) != 1)
        	{ printf ("Invalid"); return 1;}
        
        printf("Enter Upper Bound: ");
        if (scanf(" %d", &high) != 1)
        	{ printf ("Invalid"); return 1;}
        
        if ((low & 01) == 0) low++;
        
        for (; low <= high; low += 2)
        	printf("%d\n",low);
        return 0;
    }
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21