Programming code for Fahrenheit to Celsius Converters

Two programs that convert temperatures in Fahrenheit to Celsius. The first program is written in C and the second one in Python.

The C program uses dynamic memory allocation to allocate memory for the number of conversions that you want to do. I’m learning C and trying new things. Should compile in any C compiler.

#include <stdio.h>
#include <stdlib.h>

//function declarations
double * allocateIntArray(int);
void print(double *, double *, int);

int main(void){
    int num, i;
    double * arrayF;
    double * arrayC;

    printf("How many temperatures in F would you like to enter? ");
    fflush(stdout); //some systems do not print line without newline character unless you use this to force it to print
    scanf("%d",&num);

    //call memory allocation function
    arrayF = allocateIntArray(num);
    arrayC = allocateIntArray(num);
    
    printf("Please enter %d temps in F: ",num);
    fflush(stdout);

    //populate arrays
    for(i=0;i<num;i++){
        scanf("%lf", &arrayF[i]);
        //scanf("%d",arrayF+i);
        arrayC[i] = ((arrayF[i]-32)*5)/9;
    }
    print(arrayF, arrayC, num);

    //free memory
    free(arrayF);
    free(arrayC);
    return 0;
}

//allocate dynamic memory for arrays
double * allocateIntArray(int num){
    double * ptr = (double *) malloc(num * sizeof(double));
    return ptr;
}

//print output from arrays
void print(double * arrayF, double * arrayC, int num){
    int i;

    for(i=0;i<num;i++){
        printf("%.1lfF ", arrayF[i]);
        printf("%.1lfC\n", arrayC[i]);
        fflush(stdout);
    }
}

Second Python program works very similarly to the C program. I’m also learning Python programming. A very simple program with no functions.

x = int(input("How many temps?: "))

#create array to store temps in Fahrenheit
tf = []

#input temps
for i in range(x):
  tf.append(float(input()))

print("")

#calculate and print temps
for i in range(x):
  print(str(tf[i]) + "F ", end='')
  tc = round(((tf[i]-32)*5)/9, 2)
  print(str(tc) + "C")

Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *