- Ask for the size of an array;
- Create a one-dimensional array;
- Fill arrays with a random number between -6 and 6;
- Calculate and display the average value of all numbers in an array;
- Find and display the largest number from an array.
I'm new to C and can't solve the task. If it's possible can you guys help or give some hints
#include <stdio.h>
int main()
{
int size=0;
int arr[size];
printf("input size of array ");
scanf("%d",&size);
printf("\none - dimensional of array: ");
for(int i=0;i<size;i ){
scanf("%d",&arr[i]);
}
printf("\nThe array is ");
for(int i=0;i<size;i ){
printf("%d",arr[i]);
}
return 0;
}
CodePudding user response:
#include <stdio.h>
int main()
{
int max = INT_MIN; //variable to get the maximum number in the array
int avg = 0, sum = 0;
int size=0;
//Ask for size of the Array before initializing
printf("input size of array ");
scanf("%d", &size);
//Create the Array
int arr[size];
printf("\none - dimensional of array: ");
//Use rand(), to get a random number between 0 and INT_MAX
//Then modulo the value of the random int by 13 to scale the value between [0, 12]
//subtract by 6 to get a range of [-6,6]
for(int i=0;i<size;i ){
int random = rand();
random = random % 13;
random = random - 6;
arr[i] = random;
}
printf("\nThe array is ");
for(int i=0;i<size;i ){
printf("%d",arr[i]);
}
//Get average of all elements, and the element with the maximum value
for(int i=0;i<size;i ){
if(max < arr[i])
max = arr[i];
ums = arr[i];
}
avg = sum/size;
printf("\nAverage: %d", avg);
printf("\nMaximum: %d", max);
return 0;
}
CodePudding user response:
You should ask for the size before the array declaration
int size=0;
printf("input size of array ");
scanf("%d",&size);
int arr[size];
For random you could use the rand()
function from stdlib.h
to generate the elements, but you need to scale to -6 and 6 because the rand only generates values in the inclusive range [0, RAND_MAX
]. (RAND_MAX
is INT_MAX
)