Luis Geraldo Rivera Luis Geraldo Rivera - 1 month ago 9
C Question

How to get this C program to work, it keeps printing "Insert value" twice?

I'm trying to get this c program to work and it keeps printing "Insert value" twice after every output also my average doesn't work.

Here's the code:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

void main()
{
int d = 0;

printf("Command list:\t \n\nCommand: \t Output: ");
printf("\n \"A\" \t Declare values of a list.\n \"O\" \t Obtain the average value of the values in the list.\n");
printf(" \"P\" \t Print the values of the list.\n \"S\" \t End program. \n");

while (d !=1)
{
char value;

printf("\nInsert value: ");
scanf("%c", &value);


if (value == 'S' || value == 's')
{
d++;
}



float list[1000], average, sum = 0;
int number_of_values;

//in order to insert values to array:
if (value == 'a' || value == 'A')
{
printf("Insert number of values in the list: ");
scanf("%d", &number_of_values);
for (int i = 1; i<=number_of_values; i++)
{
printf("Insert Value of element %d on the list: ", i);
scanf("%f", &list[i]);
sum += list[i];

}

}

if ((value == 'P' || value == 'p') && (number_of_values >= 1))
{
for (int i =1; i<= number_of_values; i++)
{
printf("%.2f\n", list[i]);
}
}

if ((value == 'o' || value == 'O') && (number_of_values >= 1))
{
average = sum / number_of_values;
printf("Average = %.2f", average);
}


}

}

Answer

Inside while loop , leave a space before %c in this-

scanf(" %c", &value);

Your scanf returns because of '\n' present in stdin after when you press enter to give input . scanf reads until '\n' is encountered.

When you take input in array using scanf and press enter '\n' is left in buffer , and as loop iterate and it again take input in value it encounters '\n' and scanf return without taking input .That is why you need to add space before %c .

And move these declarations out of your while loop -

float list[1000], average, sum = 0;
int number_of_values;
while(b!=1){
//your code
}

If you declare variables inside loop, they get reset after every iteration due to again declaration .

Note- void main() -> int main(void) or int main(int argc,char **argv)