Can someone please help me ? I need to put the number's digits into a vector, find the smallest digit among them, and print it along with its position in the vector.
int main()
{
int n,i=0,v[100],Min=9,Position;
scanf("%d",&n);
while(n!=0)
{
v[i]=n%10;
if(v[i]<Min)
{
Min=v[i];
Position=i;
}
i++;
n=n/10;
}
printf("%d, %d", Min, Position);
printf("\n");
}
input: 1234 output: 1, 3 <---- there is the problem, i can find the minimum digit but i can't get to show its position. instead of 0 it is 3, it counts from reverse input:2314 output: 1, 1 <-- should have been 1,2
Edit: Thank you "nicomp" now the final code looks like this.
int main()
{
{
int n,m,i,v[100],Lenght=0,Min=9,Position;
scanf("%d",&n);
m=n;
while(m!=0)
{
m=m/10;
Lenght++;
}
i=(Lenght-1);
while(n!=0)
{
v[i]=n%10;
if(v[i]<Min)
{
Min=v[i];
Position=i;
}
i--;
n=n/10;
}
printf("%d, %d", Min, Position);
printf("\n");
}
}
When you go for input 1234
(your code) starts with 4
and the position becomes 0
initially and later by the time you reach to digit 1
the positions is incremented to 3
- the better approach is to read the numbers from 1 to 4 which can be done recursively, here is the code for doing that:
#include<stdio.h>
int vector[100];
int i;
int position;
int Min=9;
void locate(int num)
{
if(num>0)
{
locate(num/10);
vector[i]=num%10;
if(vector[i]<Min)
{
position = i+1;
Min=vector[i];
}
++i;
}
}
int main()
{
int n;
scanf("%d",&n);
if(n<0)
n=-n;
locate(n);
printf("Position %d Min %d\n",position, Min);
return n;
}
NOTE: When input is 1234
it shows the minimum digit's position as 1
instead as 0
as we need not to to read it as an array position but actual position.