I go web development in school and we learn the basics of C. What I share now is part of a larger task. This part is; make random numbers between 100-900, print them in a matrix 10x10 and then sort the numbers in the matrix.
I get random numbers. And numbers are sorted. But not the right numbers. It sort completely new numbers why...
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void slumptal(int slumpArray[]);
void printArray(int slumpArray[]);
void sortera(int sortArray[]);
void printsort(int sortArray[]);
/*Main, där programmet initieras */
int main(void)
{
int array[100];
srand(time(NULL)); //seed
slumptal(array);
printArray(array);
sortera(array);
printsort(array);
return 0;
}
/* Funktion som slumpar tal och sparar i array..Random numbers stored in a array*/
void slumptal(int slumpArray[])
{
for (int x = 0; x < 100; x++)
{
slumpArray[x] = rand() % 801 + 101;
}
}
/*Funktion som skriver ut matrisen.. Print the matrix*/
void printArray(int slumpArray[])
{
printf("\n");
for (int x = 1; x < 10; x++)
{
for (int y = 1; y < 10; y++)
{
printf("%4d", slumpArray[x * 10 + y]);
}
printf("\n");
}
}
/*Funktion som sorterar elementen i matrisen. Sort element in the matrix */
void sortera(int sortArray[])
{
for (int i = 0; i < 101; i++)
for (int j = 100; j > i; j--)
if (sortArray[j - 1] > sortArray[j])
{
int slask = sortArray[j - 1];
sortArray[j - 1] = sortArray[j];
sortArray[j] = slask;
}
}
/*Funktion som skriver ut sorteringen. Print the sorted numbers */
void printsort(int sortArray[])
{
printf("\n");
for (int i = 0; i < 101; i++)
{
printf("%4d", sortArray[i]);
}
}
Aucun commentaire:
Enregistrer un commentaire