Sort three variables: Difference between revisions

m (Move Python entry to correct alphabetical position.)
Line 155:
77444
---------------------------</pre>
 
=={{header|C}}==
Although C does not have a generic catch-all variable type, strings or arrays of characters can be used ( or misused ) to simulate the effect. Strings are often used to process arbitrarily large or small numbers which can't be represented by the C Standard Library. Strings are again used for this task to accept whatever the user enters. Each entry is treated as a string and is scanned. If any one of them contains a single 'non-number' character, then the whole set is treated as a set of strings.
<lang C>
/*Abhishek Ghosh, 21st September 2017*/
 
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
 
#define MAX 3
 
int main()
{
char values[MAX][100],tempStr[100];
int i,j,isString=0;
double val[MAX],temp;
for(i=0;i<MAX;i++){
printf("Enter %d%s value : ",i+1,(i==0)?"st":((i==1)?"nd":"rd"));
fgets(values[i],100,stdin);
for(j=0;values[i][j]!=00;j++){
if(((values[i][j]<'0' || values[i][j]>'9') && (values[i][j]!='.' ||values[i][j]!='-'||values[i][j]!='+'))
||((values[i][j]=='.' ||values[i][j]=='-'||values[i][j]=='+')&&(values[i][j+1]<'0' || values[i][j+1]>'9')))
isString = 1;
}
}
if(isString==0){
for(i=0;i<MAX;i++)
val[i] = atof(values[i]);
}
for(i=0;i<MAX-1;i++){
for(j=i+1;j<MAX;j++){
if(isString==0 && val[i]>val[j]){
temp = val[j];
val[j] = val[i];
val[i] = temp;
}
else if(values[i][0]>values[j][0]){
strcpy(tempStr,values[j]);
strcpy(values[j],values[i]);
strcpy(values[i],tempStr);
}
}
}
for(i=0;i<MAX;i++)
isString==1?printf("%c = %s",'X'+i,values[i]):printf("%c = %lf",'X'+i,val[i]);
return 0;
}
</lang>
The output shows three test cases, two as specified in the task, and one which mixes numbers and strings. The output is sorted considering all of them as strings in that case.
<pre>
Enter 1st value : 77444
Enter 2nd value : -12
Enter 3rd value : 0
X = -12
Y = 0
Z = 77444
 
Enter 1st value : lions, tigers, and
Enter 2nd value : bears, oh my!
Enter 3rd value : (from the "Wizard of OZ")
X = (from the "Wizard of OZ")
Y = bears, oh my!
Z = lions, tigers, and
 
Enter 1st value : -12
Enter 2nd value : bears, oh my!
Enter 3rd value : 77444
X = -12
Y = 77444
Z = bears, oh my!
</pre>
 
=={{header|C sharp}}==
503

edits