How to find the smallest digit in a number and its position in a vector in C?
How to find the smallest digit in a number and its position in a vector in C?
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");
@JohnnySmith88 You don't need one more loop to find the length of
n.– kiran Biradar
Sep 15 '18 at 11:51
n
2 Answers
2
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:
1234
4
0
1
3
#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 %dn",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.
1234
1
0
You don't need to find length of n with additional loop.
You can just subtract the position from i as below, since i will be holding the length of n.
n
position
i
i
n
int main()
int n,i=0,v[100],Min=9,Position=0;
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, (i - Position-1)); //<-----Here
printf("n");
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy
The mod operation pulls off the least significant digit first but the indexing starts from 0, the most significant digit. You need to reverse your indexing: i = (length of n) - 1 then decrement i in the body of the loop.
– nicomp
Sep 15 '18 at 11:23