c - for loop for finding smallest element in an Array -
okay program suppose create array size [8] , once printed i'm using loop find smallest number in array. problem i'm having seems stopping @ second element , declaring smallest. can tell me wrong code
#include <stdio.h> #include <stdlib.h> #include <time.h> void main(int argc, char* argv[]) { const int len = 8; int a[len]; int i; srand(time(0)); //fill array for(i = 0; < len; ++i) { a[i] = rand() % 100; } //print array (i = 0; < len; ++i) { printf("%d ", a[i]); } printf("\n"); getchar(); int smallest; (i = 1; < len; i++) { if (a[i] < smallest) smallest = a[i]; { printf("the smallest integer %d @ position %d\n", a[i], i); break; getchar(); } } }
there mistakes in code, following :
1-the variable int smallest used before initializing. 2- logic inside last loop wrong.
the right code :
void main(int argc, char* argv[]) { const int len = 8; int a[len]; int smallest; int location =1; int i; srand(time(0)); //fill array for(i = 0; < len; ++i) { a[i] = rand() % 100; } //print array (i = 0; < len; ++i) { printf("%d ", a[i]); } printf("\n"); smallest = a[0]; ( i= 1 ; < len ; i++ ) { if ( a[i] < smallest ) { smallest = a[i]; location = i+1; } } printf("smallest element present @ location %d , it's value %d.\n", location, smallest ); getch(); }
Comments
Post a Comment