0

I am working on a program that will accept user input to fill an array and then quit when the user enters q. Next the array is passed to a function that finds the largest value in the array. My program seems like it would work, but I believe that user input for the array is incorrect and I am not sure how to solve it.

#include <stdio.h>
#define SIZE 30

int maxnum(int userarray[], int maxx);


int main()
{
    int i;
    int nums[SIZE];
    int largest;


    printf("Type integer numbers (up to 30), followed by q to quit:\n");

    while(scanf("%d", &nums[i]) == 1)
    {
        for(i = 0; i < SIZE; i++)
        {
            //blank
        }
    }

    largest = maxnum(nums, SIZE);
    printf("The largest number is: %d\n", largest);

    return 0;
}

int maxnum(int userarray[], int maxx)
{
    int i;
    int maxnumber; 

    maxnumber = userarray[0];

    for(i = 1; i < maxx; i++)
    {
        if(maxnumber < userarray[i])
        {
            maxnumber = userarray[i];
        }
    }

    return maxnumber; 
}
0

2 Answers 2

3

First i is unitialized.

Then your inner for loop is strange (why someone would do that??) and sets i to SIZE in the end, which is not good.

I don't give more details, but the value of i is trash all the time because of those 2 mistakes it should be:

int i = 0;

while((i<SIZE) && (scanf("%d", &nums[i]) == 1))
{
    i++;
}

so you read one by one, and protect against array out of bounds by the second condition.

After that you're passing NUMS

largest = maxnum(nums, SIZE);

whereas the array could contain fewer valid values. Just pass

largest = maxnum(nums, i);
Sign up to request clarification or add additional context in comments.

1 Comment

how true!! fixed. Thanks
0

Here is another solution for your problem.

In main() function

int n,i=0;
  while(scanf("%d",&n) == 1){
    nums[i++] = n;
  }
n = maxnum(nums, i);
printf("The largest number is: %d\n", n);

Note : Initialize the value of i=0, Then input and update nums[] array

In maxnum() function

for(i = 0; i < maxx; i++)    {
  if(maxnumber < userarray[i]){
      maxnumber = userarray[i];
  }
}

Note: Start i=0 and find the max mumber and return the value

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.