Good day! (Yes to all interpretations thereof.)

I am a beginner at C, studying on my own because it’s fun and my goal is to “simply” gain a better understanding of how machines work under the hood. I just successfully wrote a bidirectional Celcius/Fahrenheit converter that also takes some user input. As a next step, I would like to save conversion history. Do I have to save to a file outside the program or can I temporarily save history in a variable or an array and give the user the choice to check history by displaying the contents of that variable/array? If the answer is saving to an outside file, then I digress, as this is next on my “curriculum” (still self studies). If the answer is that I can save previous input into variables or an array, how do I make a - for instance - for loop go through the elements of that array, assigning one user input (temperature conversion) in one element at a time?

Also, if this is more advanced than what I am make it sound like, please let me know, and I’ll let it be for the time being.

#include <stdio.h>  

//Function declarations  
float toCelcius(float fahrenheit);  
float toFahrenheit(float celcius);  

//Bidirectional temperature converter  

int main() {  

	int f_value;  
	int c_value;  
	int choice;  

	printf("\nWelcome to this Fantasic Bidirectional Temperature Converter!\n");  
	printf("\nWhat would you like to do? Press f + enter to convert Fahrenheit to Celcius, c + enter to convert Celcius to Fahrenheit or ctrl + c to exit: ");  
			
	while ((choice = getchar()) != EOF) {  
		if (choice != 'f' && choice != 'c') {  
			printf("Goodbye!\n"); //ctrl + c does not allow for this to be displayed.  
		}	
		if (choice == 'f') {  
			printf("\nEnter the temperature in Fahrenheit: ");  
			scanf("%d", &f_value);  
			getchar();  
			printf("\n%d degrees Fahrenheit is %.1f degrees Celcius.\n", f_value, toCelcius(f_value));  
		}  
		if (choice == 'c') {  
			printf("\nEnter the temperature in Celcius: ");  
			scanf("%d", &c_value);  
			getchar();  
			printf("\n%d degrees Celcius is %.1f degrees Fahrenheit.\n", c_value, toFahrenheit(c_value));  
		}  
		printf("\nWhat would you like to do next? Press f + enter to convert Fahrenheit to Celcius, c + enter to convert Celcius to Fahrenheit or ctrl + c to exit: ");  
	}  
	return 0;  
}  

//Function definitions  
float toCelcius(float fahrenheit) {  
	return (5.0 / 9.0) * (fahrenheit - 32.0);  
}  

float toFahrenheit(float celcius) {  
	return (celcius * 1.8) + 32;  
}  
  • mcmodknower@programming.dev
    link
    fedilink
    English
    arrow-up
    4
    ·
    edit-2
    8 hours ago

    For saving the history inside of one program run, an array is enough. For saving the history over multiple program runs (over closing by typing and invalid character or ctrl+c and restarting it), you would need to store it in a file.

    You can already print the last conversion by reading the value of f_value/c_value without writing to it (note that if no conversion of that type has happened before, you will get garbage, and that you will have to modify the if at the start of the loop to check for ‘x’ too):

    		if (choice == 'x') {  // x is the letter left of c, so i chose it as an easy example
    			// we want to print the previous conversion, so we don't want to read in a new value.
    			// printf("\nEnter the temperature in Celcius: ");  
    			// scanf("%d", &c_value);  
    			// you might need to comment this getchar() back in so your program skips over the enter after the x, but i am not sure.
    			// getchar();  
    			// no modification of the following line is needed, as the c_value of the last celcius conversion was never written too and as such still exists.
    			printf("\n%d degrees Celcius is %.1f degrees Fahrenheit.\n", c_value, toFahrenheit(c_value));  
    		}  
    

    For a longer history you need some extra places to store the numbers. if you use an array, you need to store the length of the history too, since c does not store how far into the array you have written.

    // at the start of your main function, where you also declare the other variables
    	// allocate the array with fixed length
    	int last_c_values[16];
    	// and store how many values you've written to it. Initialize it to zero so you don't do garbage with it later on.
    	int last_c_values_count = 0;
    
    // after printing the conversion from celsius to farenheit
    			if (last_c_values_count < 16) // we can't handle a history longer than that yet
    				// copy over the current value into the array, the first one will be at index 0
    				last_c_values[last_c_values_count] = c_value;
    				// increase the counter so the next value will be at the next place
    				last_c_values_count = last_c_values_count + 1;
    				// or shorter: last_c_values_count++;
    			}
    
    //and the new choice for printing the stuff
    		if (choice == 'x') {  // x is the letter left of c, so i chose it as an easy example
    			// start at 0, as long as i is below last_c_values_count, increment i by one at the end of each loop run
    			for (int i = 0; i < last_c_values_count; i++) {
    				// copy the value from last_c_values at index i into c_value
    				c_value = last_c_values[i]; 
    				// and do the same calculation as before again.
    				printf("\n%d degrees Celcius is %.1f degrees Fahrenheit.\n", c_value, toFahrenheit(c_value));  
    			}
    		}
    

    PS: the for loop in here is equivalent to the following while loop:

    			int i = 0;
    			while (i < last_c_values_count) {
    				// copy the value from last_c_values at index i into c_value
    				c_value = last_c_values[i]; 
    				// and do the same calculation as before again.
    				printf("\n%d degrees Celcius is %.1f degrees Fahrenheit.\n", c_value, toFahrenheit(c_value));  
    				i++;
    			}
    
  • lime!@feddit.nu
    link
    fedilink
    arrow-up
    3
    ·
    edit-2
    8 hours ago

    you can absolutely save history in an array, but depending on how you want to do it, it can get very complex for a beginner.

    the absolutely easiest way to go about it with how you’ve structured the program so far is making global arrays of just numbers, one for C->F conversions and one for the other way round. you also need to keep track of where in each array you are so you don’t go out of bounds. this requires minimal changes.

    float c_to_f[5] ={0,0,0,0,0};
    int c_to_f_length = 5;
    int c_to_f_index = 0;
    

    and update your input handler:

    scanf("%d", &c_value);
    c_to_f[c_to_f_index] = c_value;
    c_to_f_index++;
    if (c_to_f_index >= c_to_f_length) c_to_f_index = 0;
    

    and then when you want to see the list results, you do

    for (int i = 0; i < c_to_f_length; i++) {
        printf("%d\n", c_to_f[i];
    }
    

    this will of course not be in order of insertion, and if you want to show more than just the numbers you need to do some tinkering.

    this is however a great jumping-off point to talk about many different concepts:

    • do you feel like you’re just writing the same thing over and over? look into encapsulation and refactoring your program to minimise repetition.
    • do you want to store more information about each entry? time to learn about structs.
    • do you want to store as many entries as you want, without having to specify? go learn about linked lists.
    • do you want to be able to step back and forward through your history? check out the readline library, and learn how to do imports generally.

    sorry if my formatting is off, i did this on my phone…

        • printf("%s", name);@piefed.blahaj.zoneOP
          link
          fedilink
          English
          arrow-up
          2
          ·
          8 hours ago

          Thanks! Ultimately, down the road, I want to try Assembly and then those languages that give CPUs instruction sets. I am interested in the borders where readable code turns into binary. I just chose C to begin with because I was influenced by Linux and a colleague who used to work with C many years ago.

          • lime!@feddit.nu
            link
            fedilink
            arrow-up
            3
            ·
            7 hours ago

            ah fun! have you checked out ben eater’s ongoing youtube series of building a breadboard computer? he’s selling kits that allow you to follow along from hardware through binary, assembly, to BASIC and C. well worth a look imo.