Thread: C Homework HELP

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    1
    Rep Power
    0

    C Homework HELP


    I need help on a program. Required: Write a program that counts how many elements in an array with N elements are higher than the last element of the array. I need to use functions and the cycle for. I have done this but I can't understand what's wrong with it. Output array ex: 16 45 9 10 --> 2 Numbers are higher than the last element.
    Code:
    # include <stdio.h>
    #include <conio.h>
    int number (int i, int n)
    {
        int v[n];
        int k=0;
        int b=sizeof(v)/sizeof(v[0]);
         for (i=0;i<n;i++)
        {
            if (v[i]>v[b-1])
            k+=1;
            }
            return k;
            }
    int main ()
    {
        int n,i,k;
        printf ("Give N: ");
        scanf ("%d", &n);
        int v[n];
        for (i=0;i<n;i++)
        {
            printf ("Give the %d element: ", i+1);
            scanf ("%d", &v[i]);
            }
        
        k=number(i, n);   
        for (i=0;i<n;i++)
            printf ("%4d", v[i]);
        printf ("\n");    
        
        printf("\n %d numbers are higher than the last element.", k);
        getch ();
        return 0;
    }
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,396
    Rep Power
    1871
    cross-posted here
    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
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Posts
    15
    Rep Power
    0
    call the v array in to the function.

    Code:
    int number(int* v, int n)
    {
        int i,k=0;
        //int b=sizeof(v)/sizeof(v[0]); u know the size, why to calculate again ??
        
         for (i=0;i<n;i++)
        {
            if (v[i]>v[n-1])
            k+=1;
            }
            return k;
            }
    int main ()
    {
        int n,i,k;
        printf ("Give N: ");
        scanf ("%d", &n);
        int v[n];
        for (i=0;i<n;i++)
        {
            printf ("Give the %d element: ", i+1);
            scanf ("%d", &v[i]);
            }
        
        k=number(v,n);   
        for (i=0;i<n;i++)
            printf ("%4d", v[i]);
        printf ("\n");    
        
        printf("\n %d numbers are higher than the last element.", k);
        getch ();
    }

IMN logo majestic logo threadwatch logo seochat tools logo