Bhart Kumar
Bhart Kumar

Reputation: 25

program to print the position of the smallest number of n numbers using arrays

This code does not give me answer when i enter value 1 in array. for eg i have taken no. of elements as 5 then i enter them as 2,3,1,6,4 then output gives 2 as smallest number and position number is not always correct what's the error?

#include<stdio.h>
int main()
{
    int n,i,a[10],sum=0;
    int small=0,pos=0;
    printf("enter no of elements in array:");
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
        printf("a[%d]=",i);
        scanf("%d",&a[i]);
    }
    for(i=1;i<n;i++)
    {
        small=a[0];
        if( a[i] < small)
        {
            small=a[i];
            pos=i;
        }
    }
    printf("smallest no:%d \n",small);
    printf("position:%d",pos);

}

Upvotes: 0

Views: 8687

Answers (4)

Pratik
Pratik

Reputation: 1

You should write small = a[0] before the beginning of a for loop.

Upvotes: 0

Kamal Chandra
Kamal Chandra

Reputation: 11

small = a[0] should be before the loop.

Upvotes: 0

Kartik Agarwal
Kartik Agarwal

Reputation: 1403

You are not that far away - use are initializing small=a[0]; every time whenever loop iterates so just initialize small=a[0]; before loop Here your corrected code

   #include<stdio.h>
    int main()
    {
        int n,i,a[10],sum=0;
        int small=0,pos=0;
        printf("enter no of elements in array:");
        scanf("%d",&n);
        for(i=0;i<n;i++)
        {
            printf("a[%d]=",i);
            scanf("%d",&a[i]);
        }
small=a[0];
        for(i=1;i<n;i++)
        {

            if( a[i] < small)
            {
                small=a[i];
                pos=i;
            }
        }
        printf("smallest no:%d \n",small);
        printf("position:%d",pos);

    }

Upvotes: 0

aldarel
aldarel

Reputation: 456

"small" variable is overridden with a[0] in each iteration. Just move it outside the loop:

#include<stdio.h>

int main()
{
    int n,i,a[10],sum=0;
    int small=0,pos=0;
    printf("enter no of elements in array:");
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
        printf("a[%d]=",i);
        scanf("%d",&a[i]);
    }
    small=a[0];
    for(i=1;i<n;i++)
    {
        if( a[i] < small)
        {
            small=a[i];
            pos=i;
        }
    }
    printf("smallest no:%d \n",small);
    printf("position:%d",pos);

}

Upvotes: 1

Related Questions