end loop based on input from user - c

My program accepts a number from the user to determine the length of a sequence being recorded. How would i take that number and also let it determine the number of times this loop is performed. While(true) obviously does not allow the loop to end at all.
thanks in advance
here is the function to synthesise sound from midi input
void midisound (int note)
{
int velocity;
int playingNote = -1;
float frequency;
while(true)
{
note = aserveGetNote();
velocity = aserveGetVelocity();
if(velocity > 0)
{
frequency = 440 * pow(2, (note-69) / 12.0);
aserveOscillator(0, frequency, 1.0, 0);
playingNote = note;
}
else if(note == playingNote)
{
aserveOscillator(0, 0, 0, 0);
}
}
}
---here is where function ^ is called in the program----
if (reclayer == 1)
{
//open first text file for layer 1 to be written to
textFilePointer = fopen("recording1.txt", "w+");
if(textFilePointer == NULL)
{
printf("Error Opening File!");
}
else
{
//function call to write notes and vel data
notetofile(input, seqlen, reclayer);
printf("Would you like to record a second layer or re-record? (y or n)\n");
scanf(" %c", &choice2);
}
}

Use a for loop.
for ( i = 0; i < note; i++ ) {
// Your code here
}
This will execute 'note' number of times.

Use can use the scanf() function to input a user number from the console:
void midisound (int note) {
int input;
int velocity;
int playingNote = -1;
float frequency;
printf("Enter integer number of times to loop: ");
scanf("%d", &input);
while(input > 0) {
input = input - 1;
note = aserveGetNote();
velocity = aserveGetVelocity();
if(velocity > 0) {
frequency = 440 * pow(2, (note-69) / 12.0);
aserveOscillator(0, frequency, 1.0, 0);
playingNote = note;
} else if(note == playingNote) {
aserveOscillator(0, 0, 0, 0);
}
}
}

In that first get the number input from the user number of time loop will be run the use following
for ( i=0 ; i < max ; i++ )

First assign a variable which holds the number of times you want to repeat it. For example , let us take int n = 5;. ( You can also make the user input the value of n ( as that is what you have asked ) by calling scanf( "%d " , &n ); and then do the rest )
int n ;
scanf( "%d " , &n );
You can use this as common for all of my below cases
Then, just add a simple for loop, such as
int i;
for ( i = 0 ; i < n ; i++ )
{
// The code that you want to repeat
}
That should do the trick.
In case you want to use a while loop, then as before, let n be the number of times the loop must execute. Then
int i=0;
while ( i < n )
{
// Your code
i++;
}
You can also use the while ( true ) loop as well, but you will just have to give a condition and use break;. Let us take an example as above.
int i=0;
while ( true )
{
// your code
i++;
if ( i == n )
break;
}
These are just many of the different possibilities. You can even come up with your own condition if you try.
Happy coding .... 8-)

Related

How do I generate 4 random variables and only printing if it doesn't contain the int 0

this is my code, I want to make a function that when it is called will generate a number between 1111 to 9999, I don't know how to continue or if I've written this right. Could someone please help me figure this function out. It suppose to be simple.
I had to edit the question in order to clarify some things. This function is needed to get 4 random digits that is understandable from the code. And the other part is that i have to make another function which is a bool. The bool needs to first of get the numbers from the function get_random_4digits and check if there contains a 0 in the number. If that is the case then the other function, lets call it unique_4digit, should disregard of that number that contained a 0 in it and check for a new one to use. I need not help with the function get_random_4digitsbecause it is correct. I need helt constructing a bool that takes get_random_4digits as an argument to check if it contains a 0. My brain can't comprehend how I first do the get_random_4digit then pass the answer to unique_4digits in order to check if the random 4 digits contains a 0 and only make it print the results that doesn't contain a 0.
So I need help with understanding how to check the random 4 digits for the integer 0 and not let it print if it has a 0, and only let the 4 random numbers print when it does not contain a 0.
the code is not suppose to get more complicated than this.
int get_random_4digit(){
int lower = 1000, upper = 9999,answer;
answer = (rand()%(upper-lower)1)+lower;
return answer;
}
bool unique_4digits(answer){
if(answer == 0)
return true;
if(answer < 0)
answer = -answer;
while(answer > 0) {
if(answer % 10 == 0)
return true;
answer /= 10;
}
return false;
}
printf("Random answer %d\n", get_random_4digit());
printf("Random answer %d\n", get_random_4digit());
printf("Random answer %d\n", get_random_4digit());
Instead of testing each generated code for a disqualifying zero just generate a code without zero in it:
int generate_zero_free_code()
{
int n;
int result = 0;
for (n = 0; n < 4; n ++)
result = 10 * result + rand() % 9; // add a digit 0..8
result += 1111; // shift each digit from range 0..8 to 1..9
return result;
}
You can run the number, dividing it by 10 and checking the rest of it by 10:
int a = n // save the original value
while(a%10 != 0){
a = a / 10;
}
And then check the result:
if (a%10 != 0) printf("%d\n", n);
Edit: making it a stand alone function:
bool unique_4digits(int n)
{
while(n%10 != 0){
n = n / 10;
}
return n != 0;
}
Usage: if (unique_4digits(n)) printf("%d\n", n);
To test if the number doesn't contain any zero you can use a function that returns zero if it fails and the number if it passes the test :
bool FourDigitsWithoutZero() {
int n = get_random_4digit();
if (n % 1000 < 100 || n % 100 < 10 || n % 10 == 0) return 0;
else return n;
}
"I need not help with the function get_random_4digits because it is correct."
Actually the following does not compile,
int get_random_4digit(){
int lower = 1000, upper = 9999,answer;
answer = (rand()%(upper-lower)1)+lower;
return answer;
}
The following includes modifications that do compile, but still does not match your stated objectives::
int get_random_4digit(){
srand(clock());
int lower = 1000, upper = 9999,answer;
int range = upper-lower;
answer = lower + rand()%range;
return answer;
}
" I want to make a function that when it is called will generate a number between 1111 to 9999,"
This will do it using a helper function to test for zero:
int main(void)
{
printf( "Random answer %d\n", random_range(1111, 9999));
printf( "Random answer %d\n", random_range(1111, 9999));
printf( "Random answer %d\n", random_range(1111, 9999));
printf( "Random answer %d\n", random_range(1111, 9999));
return 0;
}
Function that does work follows:
int random_range(int min, int max)
{
bool zero = true;
char buf[10] = {0};
int res = 0;
srand(clock());
while(zero)
{
res = min + rand() % (max+1 - min);
sprintf(buf, "%d", res);
zero = if_zero(buf);
}
return res;
}
bool if_zero(const char *num)
{
while(*num)
{
if(*num == '0') return true;
num++;
}
return false;
}

Drawing an X with C with ONLY While-loops & If-Statements

An assignment we have been given is to draw an X in C using only while loops and if statements (maths and expressions are allowed).
I have only done the first half of the X in code, as the other half is just the reverse.
The challenging part is the middle dashes (-), as I'm struggling to find a way to make them count backward by 2 through while loops.
Am I overthinking this way too much? If so, what would be a better approach to this problem?
This is my first time learning C and we are not allowed for loops or anything beyond a basic level.
Thanks for reading!
int size, fLine, rowCounter, tempSize;
printf("Enter size: ");
scanf("%d", &size);
// The split will half the size of the X to run 2 seperate while loops
// One loop for the top half and another for the lower half.
int split = ((size - 1) / 2);
int row = 1;
// Top half of the X
while (row <= split) {
// Condition to print out the top and bottom line of the X
if ((row == 1) || (row == size)) {
printf("*");
// tempSize will allow for the counter to decrease without
// affecting the size variable
tempSize = size;
// Will add the middle dashes on the top line
while ((tempSize - 2) > 0) {
printf("-");
tempSize--;
}
printf("*\n");
row++;
} else {
// The dashes before the first asterisks
// rowCounter allows the row number to be decreased in the
// while loop
rowCounter = row - 1;
while (rowCounter > 0) {
printf("-");
rowCounter--;
}
printf("*");
// Will add size + (row * -2) dashes into the middle
// **This section is the subject of the question!**
rowCounter = row * 2;
tempSize = rowCounter - size; // 2 - 5 = -3
while (tempSize < (size - 1)) {
printf("-");
tempSize++;
}
printf("*");
// Will add the final dashes. Exactly the same as the first
// while loop
rowCounter = row - 1;
while (rowCounter > 1) {
printf("-");
rowCounter--;
}
printf("-\n");
row++;
} //Yet to add the middle line and the bottom half!
}
return 0;
}
Expected Result:
Enter Size: 5
*---*
-*-*-
--*--
-*-*-
*---*
Actual Result:
Enter Size: 5
*---*
-*-----*-
I want the middle values to count BACKWARD so 9, 7, 5, 3, 1, etc., instead of upwards by 2.
i have a much easier solution
#include <stdio.h>
int size, i=0, j=0;
printf("Please Enter a Odd Size: \n")
scanf(%d, &size);
while(size%2==0)
{
printf("Only Odd size is ok \n");
printf("Please Enter a Odd Size: \n")
scanf(%d, &size);
}
while(i<size)
{
j=0;
while(j<size)
{
if(j == i || i == (size-1)-j)
{
printf("!");
}
else
{
printf("-");
}
j++;
}
printf("\n\n");
i++;
}
the output is:
!---!
-!-!-
--!--
-!-!-
!---!
I messed around a little:
#include <stdio.h>
int main()
{
int size = 5;
if( size % 2 == 1 )
{
fprintf( stdout, "now drawing\n");
int lineCount = 0;
int lastPost = size - 1;
while( lineCount < size )
{
int rowCount = 0;
while( rowCount < size )
{
if( ( rowCount == lineCount )
|| ( rowCount == lastPost ) )
{
fprintf( stdout, "X");
}
else
{
fprintf( stdout, ".");
}
++rowCount;
}
fprintf( stdout, "\n");
--lastPost;
++lineCount;
}
}
else
{
fprintf( stderr, "size must be odd!\n");
}
return 0;
}

Specific dice to reroll in C

I am working on a game of Yahtzee and one part of the game is the user can choose which dice out of 5 they wish to re-roll. I don't really know how to approach this besides writing a ton of if if-else statements, but there has to be a more efficient way to re-roll the specific die/ dice. I wrote out a snippet of what I am trying to accomplish, its not exactly like this in my actual code, but hopefully it is enough to answer the question :)
#include<stdio.h>
int main(void)
{
int die1 = 0, die2 = 0, die3 = 0, die4 = 0, die5 = 0;
int *ptr_die1 = &die1, *ptr_die2 = &die2, *ptr_die3 = &die3, *ptr_die4 = &die4, *ptr_die5 = &die5;
int choice = 0;
int die[5] = { 0 };
for (int i = 0; i < 5; i++)
{
die[i] = rand() % 6 + 1;
}
printf("Die[1] = %d\n", die[0]);
printf("Die[2] = %d\n", die[1]);
printf("Die[3] = %d\n", die[2]);
printf("Die[4] = %d\n", die[3]);
printf("Die[5] = %d\n", die[4]);
choice = printf("Please select which die to reroll\n");
scanf("%d", &choice);
printf("%d\n", choice);
for (int i = 0; i < 5; i++)
{
die[choice-1] = rand() % 6 + 1;
}
printf("Die[1] = %d\n", die[0]);
printf("Die[2] = %d\n", die[1]);
printf("Die[3] = %d\n", die[2]);
printf("Die[4] = %d\n", die[3]);
printf("Die[5] = %d\n", die[4]);
return 0;
}
after this I am really lost on how to change the die because the user could want to change just 1, or all 5 or any combination in between...
You have way too many variables that are not really needed.
int main(int argc, char **argv)
{
int i;
int choice;
int dices[5];
srand(time(NULL));
while(1){
for (i = 0; i < 5; i++)
dices[i] = rand() % 6 + 1;
choice = printf("Please select which die to reroll (or enter 0 to quit)");
scanf("%d", &choice);
if (choice == 0) // end the game
break;
if (choice < 1 || choice > 5 ){ // make sure that input is valid
fprintf(stderr, "error, input should be between 1 to 5 (inclusive)\n");
return -1;
}
printf("dice shows: %d", dices[choice-1]);
}
return 0;
}
You need to ask the user for the ending it, e.g. "Enter 0 to end the game". Otherwise it would be an infinite loop.
You could have the user input a comma-separatd list of die, instead of a single integer, which it looks like you're doing now. Then just parse the input, check that you have between 1 and 5 valid integers less than 6, and index into each die.
Or you could do like kaylum suggested and loop until the user inputs a special string indicating they're done, or prompt for 1, 2, ... 5 and ask for a yes or no answer to each.
Just use an array of int values to represent the set of dice:
#define DICE_COUNT 6
void rollDice(int* diceArray, size_t diceIndex) {
assert( 0 <= diceIndex && diceIndex < DICE_COUNT );
diceArray[ diceIndex ] = rand() % 6 + 1;
}
int main(int argc, char* argv[]) {
// Seed the RNG:
srand( (unsigned)time(&t) );
int dice[DICE_COUNT];
for(size_t i = 0; i < DICE_COUNT; i++) {
rollDice( dice, i );
}
while( true ) {
printf("Please select which die to reroll. Enter -2 to quit. (%d to %d inclusive)", 1, DICE_COUNT);
int selection = -1;
scanf("%d", &selection);
if( selection == -2 ) break;
if( 1 <= selection && selection <= DICE_COUNT ) {
selection--; // convert from 1-6 to 0-5.
rollDice( dice, selection );
}
}
return EXIT_SUCCESS;
}
I don't see any if..else statements in your code above. I will say, in this chunk of code:
for (int i = 0; i < 5; i++)
{
die[choice-1] = rand() % 6 + 1;
}
You don't need the for loop. You are not using the index, and rand() should work the first time through. I know rand() isn't the best written function, but if you seed it first, it should give you a pseudo-random number.
#include <time.h>
...
/* initialize random seed: */
srand ( time(NULL) );
...
die[choice-1] = rand() % 6 + 1;
Hope this was helpful, if you are still even working on that project!

Input line freezing, segmentation fault

I'm working on a project for a class and have been stuck for quite a while. When I unit tested the input earlier, it accepted the values for numOfDataSets and createDataSets without error. Now, however, after typing in any set of values for createDataSets, the code freezes after the first input until I enter any character (such as 1 or a), then errors with a segmentation fault. I am not sure what went wrong, and I would appreciate any help.
#include <stdio.h>
#include <stdlib.h>
// Function to return the number of data sets the user wants.
int numOfDataSets(void) {
int ret;
printf("Enter number of data sets: ");
scanf("%d", &ret);
return ret;
}
// Function that creates the data sets in the input arrays.
void createDataSets(float **inputArr, int inputLength, int *lengths) {
int i = 0, j, k;
float value, *currentSet;
// For every element in inputArr...
while (i < inputLength) {
printf("Enter the number of values in this data set, followed by the values: ");
scanf("%d", &j);
*(lengths + i) = j;
currentSet = (float*)calloc(j, sizeof(float));
k = 0;
while (k < j-1) {
scanf("%f", &value);
*(currentSet + k) = value;
k++;
}
scanf("%f", &value);
*(currentSet + j - 1) = value;
*(inputArr + i) = (float*)&currentSet;
i++;
}
}
// Function to get int value of data set to choose.
int chooseDataSet(void) {
int ret;
printf("Enter the number of the data set on which you wish to do calculations: ");
scanf("%d", &ret);
ret = ret - 1;
return ret;
}
// Gets the number option of the operation that the user wants to do.
int getOption(void) {
int ret;
printf("Enter one of the following numbers:\n");
printf("1. Find the minimum value.\n");
printf("2. Find the maximum value.\n");
printf("3. Calculate the sum of all the values.\n");
printf("4. Calculate the average of all the values.\n");
printf("5. Sort the values in ascending order (i.e., from smallest to largest).\n");
printf("6. Select a different data set.\n");
printf("7. Exit the program.\n");
scanf("%d", &ret);
return ret;
}
// Function to find the minimum value of a dataset.
void minimum(float *ptr, int length) {
int i = 1;
float min;
min = *(ptr);
while (i < length) {
if (*(ptr + i) < min) {
min = *(ptr + i);
}
i++;
}
printf("The minimum value of the set is: %d\n", min);
}
// Function to find the maximum value of a dataset.
void maximum(float *ptr, int length) {
int i = 1;
float max;
max = *(ptr);
while (i < length) {
if (*(ptr + i) > max) {
max = *(ptr + i);
}
i++;
}
printf("The maximum value of the set is: %d\n", max);
}
// Function to find the sum of the values of a dataset.
void sum(float *ptr, int length) {
int i = 1;
float sum;
sum = *(ptr);
while (i < length) {
sum = sum + *(ptr + i);
i++;
}
printf("The sum of the set is: %d\n", sum);
}
// Function to find the average of the values of a dataset.
void average(float *ptr, int length) {
int i = 1;
float sum;
sum = *(ptr);
while (i < length) {
sum = sum + *(ptr + i);
i++;
}
sum = sum / length;
printf("The average of the set is: %d\n", sum);
}
// Function to sort the values of a dataset.
void sort(float *ptr, int length) {
int i = 1, j;
float temp;
while (i < length) {
j = i;
while ((j > 0) && (*(ptr + j - 1) > *(ptr + j))) {
temp = *(ptr + j);
*(ptr + j) = *(ptr + j - 1);
*(ptr + j - 1) = temp;
j--;
}
i++;
}
printf("The sorted array is: ");
i = 0;
while (i < length) {
printf("%f\t", *(ptr + i));
i++;
}
printf("\n");
}
// Main method...
int main(void) {
int *lengths, outerLength, userChoiceSet = 0, userChoiceOption = 0, breakOutterLoop = 0;
float **outer;
outerLength = numOfDataSets();
outer = (float**)calloc(outerLength, sizeof(float*));
lengths = (int*)calloc(outerLength, sizeof(int));
createDataSets(outer, outerLength, lengths);
while (breakOutterLoop == 0) {
userChoiceSet = chooseDataSet();
while ((userChoiceOption != 6) || (userChoiceOption != 7)) {
userChoiceOption = getOption();
switch (userChoiceOption)
{
case 1:
minimum(*(outer + userChoiceSet), *(lengths + userChoiceSet));
break;
case 2:
maximum(*(outer + userChoiceSet), *(lengths + userChoiceSet));
break;
case 3:
sum(*(outer + userChoiceSet), *(lengths + userChoiceSet));
break;
case 4:
average(*(outer + userChoiceSet), *(lengths + userChoiceSet));
break;
case 5:
sort(*(outer + userChoiceSet), *(lengths + userChoiceSet));
break;
case 7:
breakOutterLoop = 1;
default:
break;
}
}
}
return (0);
}
The type of input to expect from the user would be something like:
2
3 1.2 2.3 3.4
4 4.5 5.6 6.7 7.8
Your main problem is this, in createDataSets():
*(inputArr + i) = (float*)&currentSet;
What this actually does is assign the address of currentSet to each element of inputArr. This address doesn't change on each iteration, so each element of inputArr gets set to the exact same value. Moreover, this address refers to a variable local to createDataSets() which will be destroyed when that function returns, so the address will be invalid. All the arrays you're dynamically creating are just being discarded, because you're not storing the addresses.
What you should have is:
inputArr[i] = currentSet;
As you mention in the comments, your compiler warned you about this, because what you were doing was trying to store a float ** in a float *, which is rarely a good idea. By adding the cast you silenced the warning, but you didn't fix the problem it was warning you about. The number of occasions in C where a cast is actually what you want to do are relatively few. None of the casts in your program are either necessary, or wise.
A few other points...
You use the wrong format specifier in many of your printf() calls. The %d here:
printf("The minimum value of the set is: %d\n", min);
for instance, should be an %f, because min is a float.
You are overusing pointer notation which makes your code very difficult to follow. That includes very difficult for you, too. For instance, your minimum() function could be much better written as so:
void minimum(float *ptr, int length) {
float min = ptr[0];
for ( int i = 0; i < length; ++i ) {
if ( ptr[i] < min ) {
min = ptr[i];
}
}
printf("The minimum value of the set is: %f\n", min);
}
Similarly, in your switch statement, something like:
average(*(outer + userChoiceSet), *(lengths + userChoiceSet));
is much more clearly written as:
average(outer[userChoiceSet], lengths[userChoiceSet]);
You are missing a call to fflush(stdout) in a few places, where you prompt for input but do not end the prompt with an '\n'. When I ran this code on my system, the prompt did not show before it sat to wait for the input. Interactive output is line-buffered by default, in C, and if you want things to be predictable, then you need to output a '\n' or call fflush(stdout) when output needs to be displayed.
You would benefit from defining your variables closer to the time of use. Restricting the scope of your variables to the minimum feasible is generally good. For instance, in your main() function, your variable userChoiceSet is never used outside of the outer while loop, so define it inside with:
while (breakOutterLoop == 0) {
int userChoiceSet = chooseDataSet();
You don't check the return from calloc() anywhere - you must do this, because the allocation might fail. malloc() and friends return NULL on failure. There's also no real point using calloc(), here - malloc() would be more normal.
You seem to use while loops in places where for loops would be much more natural.
You haven't done too bad a job with this one, but you'll find writing larger programs easier if you make each function do just one thing. For instance, your minimum() function should just calculate the minimum, but right now it calculates it and prints it. Particularly when it comes to dealing with input in the wrong format (see point 9 below) wrapping this up in a separate function will make the functions that use that input much less cluttered, and it's easy to get a function correct and to visually debug it if it's not doing a bunch of different things at once. Also, your opportunity for reusing code goes up when you do this (e.g. right now you couldn't use that minimum() function at any place where you wanted to calculate the minimum without also printing it).
Overall, having one array for your values, and a second for their lengths, is not a good approach. Far better would be to have an array of structs, each struct having a member for the array, and a member for the length, so the two related pieces of data are packaged together.
Also, your use of scanf() is potentially troublesome. If you enter input that's not expected, your program will not fail gracefully. For instance, if you enter anything other than a number in your main menu, then you'll go into an infinite loop. Generally better is to use fgets() to read in an entire line, and use sscanf() to parse its contents. At a minimum, you should check the return from scanf() to see if it successfully read a value, and if it did not, take appropriate remedial action (like reading all the characters in the input buffer and going back to ask for more input).
Overall, bearing all of the above in mind except for the last two points, your createDataSets() function would be better looking something like this:
void createDataSets(float **inputArr, const int inputLength, int *lengths) {
for ( int i = 0; i < inputLength; ++i ) {
printf("Enter the number of values in this data set, "
"followed by the values: ");
fflush(stdout);
scanf("%d", &lengths[i]);
float * currentSet = malloc(lengths[i] * sizeof *currentSet);
if ( !currentSet ) {
perror("Couldn't allocate memory in createDataSets()");
exit(EXIT_FAILURE);
}
for ( int j = 0; j < lengths[i]; ++j ) {
scanf("%f", &currentSet[j]);
}
inputArr[i] = currentSet;
}
}
Much easier to debug, easier to follow, and easier to not get wrong in the first place.
Since I've got a bit of time on my hands, here's how I'd figure it:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>
/* Maximum length of input buffer */
#define MAX_LINE 1024
/* Dataset structure */
struct dataset {
float * data;
size_t length;
};
/* Gets a single integer from user */
int getInteger(const char * prompt)
{
int value;
bool first_try = true;
char buffer[MAX_LINE];
do {
printf("%s%s: ", first_try ? "" : "Try again - ", prompt);
fflush(stdout);
fgets(buffer, MAX_LINE, stdin);
first_try = false;
} while ( sscanf(buffer, "%d", &value) != 1 );
return value;
}
/* Gets a bounded integer from user */
int getBoundedInteger(const char * prompt, const int min, const int max)
{
bool bad_input;
int value;
do {
bad_input = false;
value = getInteger(prompt);
if ( value < min ) {
printf("Too low, try again - ");
bad_input = true;
}
else if ( value > max ) {
printf("Too high, try again - ");
bad_input = true;
}
} while ( bad_input );
return value;
}
/* Gets a list of floats from user - caller must free */
float * getFloats(const char * prompt, const int num)
{
float * values = malloc(num * sizeof *values);
if ( !values ) {
perror("Couldn't allocate memory in getFloats()");
exit(EXIT_FAILURE);
}
bool bad_input = false;
do {
printf("%s%s: ", bad_input ? "Try again - " : "", prompt);
fflush(stdout);
char buffer[MAX_LINE];
fgets(buffer, MAX_LINE, stdin);
char * ptr = buffer;
int num_read = 0;
bad_input = false;
while ( *ptr && num_read < num ) {
/* Skip leading whitespace */
while ( *ptr && isspace(*ptr) ) {
++ptr;
}
/* Get and check input */
char * endptr;
float val = strtof(ptr, &endptr);
if ( ptr == endptr ) {
bad_input = true;
break;
}
/* Advance ptr and store input if good */
ptr = endptr;
values[num_read++] = val;
}
if ( num_read < num ) {
bad_input = true;
}
} while ( bad_input );
return values;
}
/* Returns the number of data sets the user wants. */
int numOfDataSets(void)
{
return getInteger("Enter number of data sets");
}
/* Creates the data sets */
void createDataSets(struct dataset ** sets, const int set_length)
{
for ( int i = 0; i < set_length; ++i ) {
struct dataset * new_set = malloc(sizeof *new_set);
if ( !new_set ) {
perror("Couldn't allocate memory for dataset");
exit(EXIT_FAILURE);
}
new_set->length = getInteger("Enter number of values in set");
new_set->data = getFloats("Enter values", new_set->length);
sets[i] = new_set;
}
}
/* Gets the number of data set to choose */
int chooseDataSet(const int min, const int max)
{
return getBoundedInteger("Choose data set", min, max) - 1;
}
/* Gets a menu choice from the user */
int getOption(void)
{
printf("Enter one of the following numbers:\n");
printf("1. Find the minimum value\n");
printf("2. Find the maximum value\n");
printf("3. Calculate the sum of all the values\n");
printf("4. Calculate the average of all the values\n");
printf("5. Sort the values in ascending order\n");
printf("6. Output the data set\n");
printf("7. Select a different data set\n");
printf("8. Exit the program\n");
return getInteger("Choose option");
}
/* Returns the minimum value in a data set */
float minimum(const struct dataset * set)
{
float min = set->data[0];
for ( size_t i = 0; i < set->length; ++i ) {
if ( set->data[i] < min ) {
min = set->data[i];
}
}
return min;
}
/* Returns the maximum value in a data set */
float maximum(const struct dataset * set)
{
float max = set->data[0];
for ( size_t i = 0; i < set->length; ++i ) {
if ( set->data[i] > max ) {
max = set->data[i];
}
}
return max;
}
/* Returns the sum of the data in a dataset */
float sum(const struct dataset * set)
{
float sum = 0;
for ( size_t i = 0; i < set->length; ++i) {
sum += set->data[i];
}
return sum;
}
/* Returns the arithmetic average of the data in a dataset */
float average(const struct dataset * set)
{
float sum = 0;
for ( size_t i = 0; i < set->length; ++i ) {
sum += set->data[i];
}
return set->length > 0 ? sum / set->length : sum;
}
/* Sorts the elements of a dataset in place */
void sort(struct dataset * set)
{
for ( size_t i = 0; i < set->length; ++i ) {
for ( size_t j = i; j && set->data[j-1] > set->data[j]; --j ) {
float temp = set->data[j];
set->data[j] = set->data[j-1];
set->data[j-1] = temp;
}
}
}
/* Prints a dataset */
void print_set(const struct dataset * set) {
for ( size_t i = 0; i < set->length; ++i ) {
printf("%.4f ", set->data[i]);
}
putchar('\n');
}
/* Main function */
int main(void)
{
/* Get and initialize sets */
const int num_sets = numOfDataSets();
struct dataset ** sets = malloc(num_sets * sizeof *sets);
if ( !sets ) {
perror("Couldn't allocate memory for sets");
return EXIT_FAILURE;
}
createDataSets(sets, num_sets);
/* Main menu */
int chosen_set = chooseDataSet(1, num_sets);
bool keep_going = true;
while ( keep_going ) {
switch ( getOption() )
{
case 1:
printf("Minimum value is %f\n\n",
minimum(sets[chosen_set]));
break;
case 2:
printf("Maximum value is %f\n\n",
maximum(sets[chosen_set]));
break;
case 3:
printf("Sum of values is %f\n\n",
sum(sets[chosen_set]));
break;
case 4:
printf("Average of values is %f\n\n",
average(sets[chosen_set]));
break;
case 5:
sort(sets[chosen_set]);
break;
case 6:
print_set(sets[chosen_set]);
break;
case 7:
chosen_set = chooseDataSet(1, num_sets);
break;
case 8:
keep_going = false;
break;
default:
break;
}
}
/* Free memory for sets */
for ( int i = 0; i < num_sets; ++i ) {
free(sets[i]->data);
free(sets[i]);
}
free(sets);
return 0;
}

C: How to sort file by lowest number (using structures)?

So what I'm trying to do is to find out how to sort a file by lowest number. The numbers are inside a struct. The program is sort of a scoreboard. You can add a name and you include the score (in this case its about runners and time taken).
After adding the names the program sorts the scores and runners by best time into a file.
Im having trouble figuring out how to:
Sort them by lowest/highest.
Keep the runners name intact with their score after sorting it.
To the code:
#include <stdio.h>
#include <string.h>
struct kilpailijat //The structure im using
{
char nimi[43+1];
float aika;
};
int main() {
int i, maara;
struct kilpailijat henkilo[50];
FILE *tulos;
size_t ln;
while (1 != 0) {
printf("Montako kilpailijaa haluat lisätä? (max 50): "); //How many runners
scanf_s("%d", &maara); // User input of how many runners
while (getchar() != '\n');
if (maara > 50) { //Checks that the ammount of runners is no more then 50
printf("Yritit lisätä liian monta kilpailijaa.\n");
} else if (maara < 0) { //And no less then 0
printf("Mielenkiintoista. Jos yrittäisit uudelleen.\n");
} else if (maara == 0) { // Zero Quits the program
return 0;
} else {
break;
}
}
for (i = 0; i < maara; i++){ // Start loop to add runners and their score.
printf("\nAnna kilpailijan nimi: ");
fgets(&henkilo[i].nimi[0], 43, stdin); //Add name of runner
ln = strlen(henkilo[i].nimi) - 1; //Remove newline off of fgets()
if (henkilo[i].nimi[ln] == '\n'){
henkilo[i].nimi[ln] = '\0';
}
printf("Kilpailijan aika: "); //Add score
scanf_s("%f", &henkilo[i].aika);
while (getchar() != '\n');
}
if ((tulos = fopen("tulos.txt", "w")) == NULL){ // Check if file opens
printf("Tiedoston avauksessa tapahtui virhe.\n");
}
for (i = 0; i < maara; i++){ //Writes Name and Score to file.
fprintf(tulos, "%s\t%.1f\n", henkilo[i].nimi, henkilo[i].aika);
}
fclose(tulos);
}
Use qsort and implement a custom compare method.
int compare (const void * a, const void * b)
{
float f1 = ((struct kilpailijat *)a)->aika;
float f2 = ((struct kilpailijat *)b)->aika;
int result = 0;
if (f1 < f2)
{
result = -1;
}
else if (f1 > f2)
{
result = 1;
}
return result;
}
And then:
qsort (henkilo, maara, sizeof(kilpailijat), compare);
Update:
Ladies and Gentlemen, I'm proud to present a working example.
It uses three languages that I'm not particularly familiar with... Finnish, English and C!
To build on Anthony Accioly's answer, but using my favorite operator.
int compare (const void * a, const void * b)
{
float f1 = ((struct kilpailijat *)a)->aika;
float f2 = ((struct kilpailijat *)b)->aika;
return f1 < f2
? -1
: f1 > f2
? 1
: 0;
}

Resources