How to fill an array from user input??

Member Avatar for Mouche

Please give some effort when you post a question. This is a simple task you could learn by reading a book on C. You need to read in characters from the user and then store those values in the array. Look into fgets() and getchar().

ok i try it. but i don't want to use fgets() and getchar(). I need to display the smallest and largest value in the array.
the program does not contain error but it is not displaying the correct values. Whats wrong with it?

#include<stdio.h>

int main ()

	{

		int A[10];
		int x,i;
		int largest,smallest;

		for (i=0;i<10;i++)

		{	

			printf ("Enter the values of the Array: ");	

			scanf ("%i",&x);

			A[i]=x;

		}

		A[0]=largest;

		for (i=0;i<10;i++)

		{
			

			if (A[i]>largest)

				{

					largest=A[i];

				}

			if (A[i]<largest)

				{

					smallest=A[i];

				}

		}
		printf("Largest: %i  ",largest);
		printf("Smallest: %i \n",smallest);
	

	}
Member Avatar for Mouche

You never initialize the variable "largest". On line 23, you assign A[0] to an uninitialized value. When you go through A to find the largest value, A[0] could be anything. When I tested it, it was 32767.

I recommend compiling with the compiler option -Wall. That enables all warnings. When I compiled with that option while using GCC 4.4.3, it said this:

$ gcc -Wall -o array_sizes array_sizes.c
array_sizes.c: In function ‘main’:
array_sizes.c:51: warning: control reaches end of non-void function
array_sizes.c:23: warning: ‘largest’ is used uninitialized in this function

That second warning tells you that you're using an uninitialized variable.

am a bit confused. i assign A[0] to which value?

How about swapping

A[0]=largest;

to

largest= A[0];

largest= A[0];
it is a start and i think line 38 is use less instead of an other "if" you can go on with else smallest=A

Member Avatar for Mouche

You should initialize both largest and smallest as one of the items in the array (A[0], for example) as a starting point.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.