Thread: How to locate a negative number in an array?

  1. #1
    Registered User
    Join Date
    Dec 2014
    Posts
    33

    How to locate a negative number in an array?

    Using floats, I'm trying to have a user fill an array. Then have a user input an element they want to know the location of.
    It works fine for decimal inputs but when I input a negative number it doesnt find it in the array

    Code:
    #include<stdio.h>
    
    int main() {
    
    
        int n, i;
        float array[100], elem;
    
    
        printf("Enter the number of elements in an array:\n");
        scanf("%d", &n);
    
    
        printf("Enter the values of each element:\n");
        for(i=0;i<n;i++){
            scanf("%f", &array[i]);
        }
        printf("\n");
        printf("which element are you looking for?\n");
        scanf("%f", &elem);
    
    
        i=0;
        while(i<n && elem != array[i]){
            i++;
        }
    
    
        if(i<elem)
            printf("Your element is located at element: %d", i);
    
    
        else
            printf("-1");
    
    
       return (0);
    
    
        }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    If elem is negative, when do you expect this to be true?
    Code:
        if(i<elem)
            printf("Your element is located at element: %d", i);
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Dec 2014
    Posts
    33
    Quote Originally Posted by Salem View Post
    If elem is negative, when do you expect this to be true?
    Code:
        if(i<elem)
            printf("Your element is located at element: %d", i);
    Gotcha, it would never work.
    Changed the variable to n and now it works. LOL.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Read until negative number
    By m_user in forum C Programming
    Replies: 10
    Last Post: 04-03-2009, 06:38 AM
  2. Help locate an ideal large number class
    By simpleid in forum C++ Programming
    Replies: 2
    Last Post: 08-08-2007, 08:05 AM
  3. How can i convert negative number to positive number ?
    By winsonlee in forum C Programming
    Replies: 2
    Last Post: 05-05-2004, 08:02 AM
  4. random number between negative and positive number
    By anomaly in forum C++ Programming
    Replies: 6
    Last Post: 12-06-2003, 08:40 AM
  5. how to read in a negative number using cin
    By revelation437 in forum C++ Programming
    Replies: 4
    Last Post: 04-02-2003, 02:32 PM