Tuesday, July 14, 2009

Write a program in C using one-D. array that prints the difference of the five input values from the lowest.?

Write a program in C using one-dimensional array that determines the lowest among five input values and prints the difference of the five input values from the lowest.





Sample input: 45793


Sample output:


1


2


4


6

Write a program in C using one-D. array that prints the difference of the five input values from the lowest.?
#include%26lt;stdio.h%26gt;


#include%26lt;stdlib.h%26gt;





#define INPUT_SIZE (5)





int main()


{


int nIndex;


int Input[INPUT_SIZE];


int nMinIndex = -1;


int nMinVal = 10;





printf("Enter Number of 5 digits:");


for(nIndex = 0; nIndex %26lt; INPUT_SIZE; nIndex++)


{


scanf("%1d",%26amp;Input[nIndex]);


/* Save Lowest Value */


if(Input[nIndex] %26lt; nMinVal)


{


nMinVal = Input[nIndex];


nMInIndex = nIndex;


}


}


printf("Output:");


for(nIndex = 0; nIndex %26lt; INPUT_SIZE; nIndex++)


{


if(nIndex != nMInIndex )


{


printf("%d\r\n", Input[nIndex] - nMinVal);


}


}


return (0);


}
Reply:The easiest way to do this would be to loop through the array once, finding the lowest value, then loop through again printing out the differences.





It should only take a few lines of code.
Reply:#include %26lt;stdio.h%26gt;


#include %26lt;stdlib.h%26gt;





int


compare(const void *elem1,const void *elem2){


if((*(int *)(elem1)) %26lt; (*(int *)elem2))


return(-1);


if((*(int *)(elem1)) %26gt; (*(int *)elem2))


return(1);





return(0);


}








int


main(int argc, char *argv[]){


int ii=0;


int arr[6]={0,0,0,0,0};





/* Handle under flow or overflow */


if(argc%26lt;2 || argc%26gt;6)


return(-1);





for(ii=0;ii%26lt;(argc-1);ii++)


arr[ii]=atoi(argv[ii+1]);





qsort((void *)arr,5,sizeof(int),compare);





for(ii=1;ii%26lt;5;ii++)


printf("%d\n",arr[ii]-arr[0]);





return(0);


}
Reply:#include%26lt;math.h%26gt;


main()


{


int i,a[5];


clrscr();


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


{


printf("Enter the number::");


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


}


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


printf("%d",abs(a[i]-a[i+1]));


getch();


}


No comments:

Post a Comment