What I'm tryng to make: I'm trying to do a program that analyzes and give some relevant information about any given set of numbers.
To make it useful not only for the purpose of my research, I'm writing it to generate a random array of any given number of elements. Afterwards I'm planning to put the option for it to process a file with its set of numbers.
What is my question: The problem that brings me here is that when I'm asked to repeat, modify the array size or to quit the program it only respond accordingly on the second input and I have no clue on what reason would be for this behavior.
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
/*This program creates an array, calculates its standard deviation and identify its large element.*/
int DV(int n){ /*DV -> Compute the standard deviation, identify the large element and its respective position*/
int i, l, p = 0;
float x[n], MVx = 0, j = 0, k = 0;
char rst;
printf("Be a random array with %d elements, created from 0 to %d: \n", n, n-1);
for(i = 0; i < n; i++){ //Generates an array with n random elements
x[i] = rand() % n;
MVx += x[i];
printf("%.0f ", x[i]);
}
MVx /= n; // Here MV assumes the Arithmetic mean
printf("\nThe arithmetic mean is: %.5f\n", MVx);
for (i = 0; i < n; i++) {
j = x[i] - MVx;
j *= j;
k += j;
}
printf("The standard deviation is %.5f\n\n", sqrt(k/n));
j = 0; // j needs to be reseted
for(i = 0, l = i + 1; i < n - 1, l < n; i++, l++){ //Compares all elements and puts its largest value on j
switch (x[i] > x[l]){
case 1: if(j < x[i]){ j = x[i]; p = i;} break;
case 0: if(j < x[l]){ j = x[l]; p = l;} break;
}
}
printf("The largest value on sample is: %.2f\nIt occurs for the first time on the %dº element\n", j, p+1);
printf("\n\nRepeat? (y/n)\nA/a to change array size: ");
while((getchar()) != '\n');
rst = getchar();
switch (rst) {
case 'N':
case 'n': return 1; break;
case 'A':
case 'a': return 2; printf("\n\n"); break;
case 'Y':
case 'y': return 3; printf("\n\n"); break;
default: return -100;
}
}
int main(void){
int n;
char rst = 'a', qtd = 'a';
while(rst == 'a') {
if(qtd == 'a'){
printf("Insert the amount of elements to be computed: ");
scanf("%d", &n);
}
srand(time(NULL)); //Generates randomic seed
DV(n);
switch(DV(n)){
case 3: printf("\n\n"); rst = 'a'; qtd = 'n'; break;
case 2: printf("\n\n"); rst = qtd = 'a'; break;
case 1: printf("\n\n"); return 0; break;
default: printf("Invalid entry\n\n"); return 0;
}
}
}