BELOW IS THE ASSIGNMENT:
Write a program to print the last element in an array of doubles. The array should have a dynamic length. The length should be taken from a command line argument. If no command line argument is provided to your program, the array length should be 5. The array should be created dynamically and filled with values starting with 0.0 -> 0.1 -> 0.2 ......
Example:
Call your program: mycalc.exe 42
Output of your program will be in this example: My last array element is: 4.1
However, when I run this code, it always shows 0.0 no matter how I change my command line argument or even I have no command line argument. What is the problem, can anybody correct my code, please. I'm in a hurry, thank you so much.
BELOW IS THE CODE I WROTE:
#include <stdio.h> // standard input/output functions
#include <string.h>
#include <stdlib.h>
#define last_digit_of_Matrikelnummer 5
int main(int argc, char* argv[])
{
int i;
int DynArraylen;
double* DynArray;
if (argc == 1)
{
DynArraylen = last_digit_of_Matrikelnummer;
DynArray = (double*)malloc(DynArraylen * sizeof(double));
DynArray[0] = 0.0;
for (i = 1; i < DynArraylen; i++)
{
DynArray[i] = DynArray[i - 1] + 0.1;
}
printf("My last array element is: %.1f\n", DynArray[i]);
//Free memory
free(DynArray);
}
else if (argc == 2)
{
//Dynamic memory allocation
DynArraylen = (int)argv[1];
DynArray = (double*)malloc(DynArraylen * sizeof(double));
DynArray[0] = 0.0;
//check
if (DynArray == NULL)
{
printf("out of memory\n");
}
else
{
DynArray[0] = 0.0;
for (i = 1; i < DynArraylen; i++)
{
DynArray[i] = DynArray[i - 1] + 0.1;
}
printf("My last array element is: %.1f\n", DynArray[i]);
}
//Free memory
free(DynArray);
}
return 0;
}