Am trying to write a c program to do the following;

• Write on the screen: ``Please enter a positive number: ''.
• Accept a number from the user.
• Keep prompting for more numbers until -1 is entered
• Output the sum of all entered numbers excluding -1.
• Output the integer part of the average of all entered numbers excluding -1.
• The program should properly check all input provided by the user and fail appropriately
if bad input is given. The user should not be able to induce a segmentation fault or
unintended behaviour from the program

I have written some code but the output seems wrong. here is my code below;

``````#include <stdio.h>
#include <stdlib.h>

#define LENGHT 10

int main(void) {

int pnumbers[LENGHT] = {0};
int i,j,k, sum = 0, input, count = 0, integers = 0;
float check;

i = 0;
while (i < LENGHT) {
i++;

scanf("%d", &input);

if(input == -1)
{ break;}

if(input%2 == 0 || input%2 != 0)
pnumbers[i] = input;
else
break;

}

for(j = 0; j < LENGHT; j++) {
sum = sum + pnumbers[j];
}
printf("\nSum = %d", sum);

for(k = 0; k < LENGHT; k++) {

if(pnumbers[k]%2 == 0 || pnumbers[k]%2 != 0) {
count = count + 1;
integers = integers + pnumbers[k];
}
}

printf("\nAverage of integers = %d", integers/count);

return 0;
}
``````

You don't need an array. lines 14, 15 and 16 is the wrong kind of loop. There is no restriction on the number of integers that can be entered. You could enter a billion numbers if you desire.

You only have to keep track of 2 things: sum of the numbers entered, and how many numbers you entered. Each time you enter a positived number just add it to the sum counter. No reason to save the numbers in an array.

line 26: `if(input%2 == 0 || input%2 != 0)`

What is that supposed to do? Since there is no other possibility that line is pretty much useless and the break on line 29 will never get executed.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.