WRITE A PROGRAM that counts the number of negative values, the number of positiv
ID: 3814179 • Letter: W
Question
WRITE A PROGRAM that counts the number of negative values, the number of positive values and the number of zeros in a float array. Specificially, the program should: • greet the user, • prompt for and input the length of the array; • idiotproof the length of the array; • dynamically allocate the array; • check that the allocation was successful; • prompt for and input the values in the array; • count the number of negative values; • count the number of positive values; • count the number of zeros; • output the numbers of negative, positive and zero values in the array; • deallocate the array. HINT: To determine how many of the input values have a particular property, you need to examine each value in turn to see whether it has that property. Specifically: 1. Before you start examining the input values, the number of input values that you’ve examined so far that have that property is zero. 2. Examine each input value in turn. If it has the property, then the number of input values that you’ve examined so far that have that property increases by one. NOTE: You MUST calculate each of the three counts in its own for loop; you are ABSOLUTELY FORBIDDEN to calculate more than one of them in the same for loop.
Explanation / Answer
// C code
#include <stdio.h>
#include <stdlib.h>
int main()
{
int length;
printf("Please enter the length of the array: ");
scanf("%d",&length);
if(length<=0)
{
printf(" Please enter positive value for the length of array.");
printf(" Quiting the program!!");
return 0;
}
else
{
float * arr;
arr = (float *) malloc(length);
if (arr == NULL)
{
// error assigning memory. Take measures.
printf(" Error while creating array dynamically");
printf(" Please chekc your Memory. Quiting!!");
}
else
{
printf(" Array allocation dynamically is successfull");
printf(" Enter values of array (float): ");
for(int i=0;i<length;i++)
scanf("%f",&arr[i]);
int negativeNos =0,positiveNos=0, zeroCount=0;
for(int i=0;i<length;i++)
{
if(arr[i] <0)
negativeNos++;
}
for(int i=0;i<length;i++)
{
if(arr[i] >0)
positiveNos++;
}
for(int i=0;i<length;i++)
{
if(arr[i] == 0)
zeroCount++;
}
printf(" Number of neagtive numbers are: %d",negativeNos);
printf(" Number of positive numbers are: %d",positiveNos);
printf(" Number of zero numbers are: %d",zeroCount);
printf(" Deallocating the array ");
free(arr);
}
}
return 0;
}
/*
output:
Please enter the length of the array: 5
Array allocation dynamically is successfull
Enter values of array (float):
3.4
5
-1
0
1
Number of neagtive numbers are: 1
Number of positive numbers are: 3
Number of zero numbers are: 1
Deallocating the array
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.