How to fill an array from user input??

Edited 5 Years Ago by techyworld: n/a

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().

Edited 5 Years Ago by Mouche: n/a

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);
	

	}

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.

Edited 5 Years Ago by Mouche: n/a

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

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

This article has been dead for over six months. Start a new discussion instead.