Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

C Programming: Write a program to dynamically allocate space by calling: malloc

ID: 659699 • Letter: C

Question

C Programming: Write a program to dynamically allocate space by calling: malloc to read a number of floating point numbers and display them in reverse order. Your program should be design based of the following steps:

1. Declare a struct named: rec with the following fields:

A variable of type of a pointer to the type float named: x.

A variable of type integer named: size.

2. Declare a variable of the of type: rec named: a

3. Prompt the user the following message:

Enter the number of floating point numbers:

4. Read a positive integer: n for the filed: size.

Note: By: n I mean a positive integer.

5. Use the built-in function malloc to create n consecutive locations of type float and let the filed: x points to the first location of these consecutive locations. This makes the filed: x an array of type float with the size: n.

6. Read n floating point numbers into the filed: x.

7. Display the floating numbers in reverse order. The decimal part of each number should have 3 digits.

Sample dialog:

Enter the number of floating point numbers: 5

Enter 5 floating point numbers:

12.5 -77.85 23 -65.43 26.31

The numbers in reverse order are:

26.310

-65.430

23.000

-77.850

12.500

Explanation / Answer

#include <stdio.h>

struct rec

{ float *x;

int size;

};

int main()

{

struct rec a;

printf("Enter the number of float nos ");

scanf ("%d", &n);

x=(float *) malloc (n*sizeof(float));

printf("Enter %d float numbers", n);

for (i=0; i<n; i++)

scanf("%f",(x+i));

for( i=n; i>0; i--)

printf ("%f", *(x+i));

free(x);

}