Sunday, August 2, 2009

Write a program to find the smallest and largest element in a given array in c language?

Array myArr = new int[5] { 3, 5, 1, 2, 4 };


int hiVal = null;


int loVal = null;


for (int i = 0; i %26lt; myArr.Length; i++) {


int curVal = myArr[i];


if (i == 0) { // Initial


hiVal = curVal;


loVal = curVal;


} else {


if (curVal %26lt; loVal) loVal = curVal;


if (curVal %26gt; hiVal) hiVal = curVal;


}


}

Write a program to find the smallest and largest element in a given array in c language?
#include%26lt;stdio.h%26gt;


void main()


{


int a[10],n,i,large,small;


printf("enter the value of n\n");


scanf("%d",%26amp;n);


printf("enter the elements\n");


for(i=0;i%26lt;n;i++)


scanf("%d",%26amp;a[i]);


large=a[0];


small=a[0];


for(i=1;i%26lt;n;i++)


{


if(a[i]%26gt;large)


large=a[i];


if(a[i]%26lt;small);


small=a[i];}


printf("largest element in the array id %d\n",large);


printf("smallest element in the array is %d\n",small);


}
Reply:I guess you're hoping homework can be this easy, eh? Not a chance. Time for you to learn something instead... %26gt;:-)





All you need to do is create placeholders that store "the smallest so far" and "the largest so far", which are of course going to be the same type as your array (probably 'int').





Initialize the "smallest_so_far" to the largest possible number (surprise, there's a macro for that! it's called "INT_MAX"), and initialize the "largest_so_far" variable to the smallest possible number (can you guess to what? That's right -- "INT_MIN").





Then, just iterate through your array (from index 0 to index n-1, where n is the number of elements in your array), and for each number, ask "is this number less than smallest_so_far? if so, smallest_so_far is now equal to this number" and do the same for the largest (except, of course, your comparison will be the opposite).





How do you figure out how many elements are in your array?





It's a classic, watch:





int my_array[] = { 1, 7, 37, 2, 14, 59 };





int my_array_item_count = sizeof(my_array) / sizeof(my_array[0]);





See what's happening there? You are dividing the total size of the array (always in octets, sometimes called "bytes") by the size of the first item (it doesn't have to be the first, but every array starts with the first, so why not?) to get the number of items, even though we didn't know off-hand -- the compiler calculates it for us! (and there's not runtime cost in this case, because the compiler has all the info it needs at hand when compiling).

savage garden

No comments:

Post a Comment