Program runs but asks for input twice - c

i have written the following program however every time i run it, the for loops do not work until i enter another number. The for loops then run, using the second number entered. why is this happening? no one seems to be having this problem... here is the program:
#include <stdio.h>
#include <math.h>
int main(void)
{
float limit;
float count;
float series1, series2;
printf("Enter a limit for the series ");
scanf ("%f", &limit);
while (scanf ("%f", &limit) == 1)
{
for (series1 = 1, count = 2; count <= limit; count++)
series1 += 1.0/count;
printf ("\nThe sum of the first infinite series is %.4f", series1);
for (series2 = 1, count = 2; count <= limit; count++)
series2 += (1.0/count) * pow ((-1),(count - 1));
printf ("\nThe sum of the second infinite series is %.4f", series2);
printf("\n\nEnter a limit for the series (q to quit) ");
scanf ("%f", &limit);
}
return 0;
}

Your problem is right here:
scanf ("%f", &limit);
while (scanf ("%f", &limit) == 1)
The while loop is going to execute that scanf everytime it starts, so just lose the first scanf.

When you run the while loop while (scanf ("%f", &limit) == 1) it is running scanf ("%f", &limit) == 1 again, after you have already ran it. Try setting the first scanf to output a variable and run the variable in the while loop.

Related

For loop assistance + accumulation

I'm very new to programming (so I apologize in advance), and I am having trouble figuring out how to make a for loop that will do the following:
I'm asking the user to input two variables (i'll call them x & y), which I then am calculating x/y = z. I want to pose this two variable input question 3 times, and then add up the 3 z to find the average. (The later part about accumulating/averaging I can figure out, but getting a for loop to repeat and give z three times is stumping my extremely novice mind. So far I can only get the for loop to ask for the two variable inputs one time, spit out z, and then terminate (I haven't attempted the averaging of z yet, because I don't have more than one z at this time).
To make things clearer, here's what I've got:
#include <stdio.h>
int main(void)
{
float x, y, z;
int c;
printf ("Enter x: ");
scanf ("%f", &x);
while ( (c = getchar() != '\n') && c != EOF);
printf ("Enter y: ");
scanf ("%f", &y);
while ( (c = getchar() != '\n') && c != EOF);
for (; x <3; x++)
{
z = x / y;
printf("Your average is %f\n", z);
}
printf("Thank you for using the program. Goodbye\n" );
getchar();
return 0;
}
Thanks for your help!!
#include <stdio.h>
int main(void)
{
float z[3];
for (int i = 0; i < 3; ++i)
{
float x, y;
printf ("Enter x: ");
scanf ("%f", &x);
printf ("Enter y: ");
scanf ("%f", &y);
z[i] = x / y;
printf("Your average is %f\n", z[i]);
}
printf("Your overall average is %f\n", (z[0] + z[1] + z[2]) / 3);
printf("Thank you for using the program. Goodbye\n" );
getchar();
return 0;
}

scanf function not working with characters

I was just trying out a simple program in C, inserting into an array.
I used a scanf function to accept characters but it seems the compiler just skipped that and just went to end of the program.
This was the code that I used :-
#include <stdio.h>
void main()
{
int a[50], i, j, m, n, x;
char ch;
printf("Enter the no. elements of the array :- ");
scanf("%d", &m);
printf("Enter the elements below :- ");
for (i = 0; i < m; i++)
{
scanf("%d", &a[i]);
}
printf("The array is :- \n");
for (i = 0; i < m; i++)
{
printf("%d", a[i]);
}
printf("\nDo you want to enter an element ? (Y/N)\n");
scanf("%c", &ch); // The compiler just skips this along with the
while (ch == 'y' || ch == 'Y') // while loop and goes straight to the printf
{ // statement
printf("The index of the element :- ");
scanf("%d", &n);
printf("\nEnter a number :- ");
scanf("%d", &x);
for (i = m; i > n; i--)
{
a[i] = a[i - 1];
}
a[n] = x;
printf("\nInsert more numbers ? (Y/N)");
scanf("%c", &ch);
m = m + 1;
}
printf("\nThe array is :- ");
for (i = 0; i < m; i++)
{
printf("%d", a[i]);
}
}
I used the variable ch in order to allow the user to have a choice, whether or not to insert elements i.e. Y or N.
But the compiler basically skips the third scanf function, the one that accepts the char, along with the while loop.
I just want to know why the scanf function was skipped ?
Back to the previous scanf which is the last array member.
scanf("%d",&a[i])
In the input file if you entered:
32\n
^^
input will wait just before the newline after reading the decimal number.
In the scanf which causes problem:
scanf("%c", &ch);
It will read the newline character as it is available in input that's why it will skip that line after being executed implicitly.
To ignore the whitespace you have only to add space before the specifier %c as stated in comment by #xing and #WeatherVane.
scanf(" %c",&ch);
C99 7.19.6.2
Input white-space characters (as specified by the isspace function)
are skipped, unless the specification includes a [, c, or n
specifier.250)

Loop repeating scanf and printf

I've written a program that will scanf twice before printf and will output two of what should be a single printf. The issue seems to begin occurring from the point that asks the user to input a number between 1 to 4 to see the average temperature for the entered number of days.
I'm not sure what's causing this double inputs and outputs and the occasional delays. Here's my code:
#include <stdio.h>
#include <stdlib.h>
int main (void) {
int i;
int limit;
int day[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int high[10], low[10];
printf("---===IPC Temperature Analyzer V2.0===---\n");
printf("Please enter the number of days between 3 and 10, inclusive: ");
scanf("%d", &limit);
while (limit <= 2 || limit >= 11) {
printf("Invalid entry, please enter a number between 3 and 10, inclusive: ");
scanf("%d", &limit);
}
for (i = 0; i < limit; i++) {
printf("Day %d - High: ", day[i]);
scanf("%d", &high[i]);
printf("Day %d - Low: ", day[i]);
scanf("%d", &low[i]);
}
printf("\nDay Hi Low\n");
for (i = 0; i < limit; i++) {
printf("%d %d %d\n", day[i], high[i], low[i]);
}
int max = 0;
int min = 0;
for (i = 0; i < limit; i++) {
if (high[max] < high[i])
max = i;
if (low[min] > low[i])
min = i;
}
printf("\nHighest temperature was: %d on day %d\n", high[max], day[max]);
printf("Lowest temperature was: %d on day %d\n", low[min], day[min]);
int n;
do {
printf("\nEnter a number between 1 and 4 to see the average temperature "
"for the entered number of days, enter a negative number to exit:");
scanf("%d\n", &n);
while (n > 4) {
printf("Invalid entry, please enter a number between 1 and 4, inclusive: ");
scanf("%d", &n);
}
while (n < 0) {
printf("Goodbye!\n");
exit(0);
}
float avgSum = 0.0;
for (i = 0; i < n; i++) {
float avgOfDay = (high[i] + low[i]) / 2.0;
avgSum += avgOfDay;
}
float overallAvg = avgSum / n;
printf("The average temperature up to day %d is: %.2f\n", day[n - 1], overallAvg);
} while (n > 0 || n < 4);
return 0;
}
Example output:
Enter a number between 1 and 4 to see the average temperature for the entered number of days, enter a negative number to exit:5
5
Invalid entry, please enter a number between 1 and 4, inclusive: Invalid entry, please enter a number between 1 and 4, inclusive: 3
The average temperature up to day 3 is: 2.50
Enter a number between 1 and 4 to see the average temperature for the entered number of days, enter a negative number to exit: 2
2
The average temperature up to day 2 is: 2.75
Enter a number between 1 and 4 to see the average temperature for the entered number of days, enter a negative number to exit: -1
The average temperature up to day 2 is: 2.75
Enter a number between 1 and 4 to see the average temperature for the entered number of days, enter a negative number to exit: -1
Goodbye!
The problem you are describing can be traced to the scanf() statement at the beginning of the do loop:
scanf("%d\n", &n);
The newline at the end of the format string is the trouble. When scanf() encounters a white-space character in the format string, it matches white-space characters in the input stream until a non-white-space character is encountered. The problem is that when you press the enter key to input your number, this is just another white-space character, so scanf() greedily continues waiting for more input, until either a non-white-space character, or EOF is encountered. When the user enters a non-white-space character at this point, the scanf() white-space match fails, the entered character remains in the input stream, scanf() finally returns to the calling function, and at last, the next scanf() picks up the character that was just rejected. This is the cause of the sporadic response that you observed.
The fix for this is simple. Just remove the \n from the end of the format string. It is usually the case that a white-space character at the end of a format string is the wrong thing to do.
There are other issues in the code. The test at the end of the do loop should be:
while (n > 0 && n < 4);
The test for an exit value would be better as an if statement instead of a while loop, and the test should be for n < 1 instead of n < 0 to avoid a division by zero error:
if (n < 1) {
printf("Goodbye!\n");
exit(0);
}
It seems that you should change the input prompt to:
printf("\nEnter a number between 1 and 3 to see the average temperature for the entered number of days, enter a negative number to exit:");
If the user chooses 4 here, but only entered data for 3 days, the calculation will access uninitialized values in the high[] and low[] arrays. You will also need to change this input loop to:
while (n > 3) {
printf("Invalid entry, please enter a number between 1 and 3, inclusive: ");
scanf("%d", &n);
}
There may be other issues, but this should get things running.
while (n > 0 || n < 4); => while (n > 0 && n < 4);
I was able to determine the solution to my problem. The new line function next to the scanf and printf of some parts of my code were causing the program to reiterate certain scanf and printf functions.
scanf("%d\n", &n) =>
printf("%d", &n)
printf ("The average temeprature up to day %d is: %.2f\n", day[n-1], overallAvg); =>
printf ("The average temeprature up to day %d is: %.2f", day[n-1], overallAvg);

Warning: Comparison between pointer and integer in while loop

I'm writing a program that asks the user to input the high and low temperatures over the course of three days. The high temperature for each day has to be greater than the low, the high must not be greater than 41 and the low must not be less than negative -41.
I wrote a while statement following the inputs for the first day however, I get the error comparison between pointer and integer.
I figured it had something to do with me using a set integer so I tried just making a while statement that involved high being greater than low, which resulted in the program working, but I found the while loop was skipped entirely. Here's my code so far:
Edit: I'm beginning to understand where my while loop went wrong. I believe it was because I neglected to assign a value from the array to the high and low and I also neglected to have the code rerun if the user met the conditions for the while loop. Initially, I had wrote it so the high and low held no value and the while condition was trapped in an infinite loop because I did not give it something to execute following the conditions being met.
#include <stdio.h>
#define NUMS 3
int main (void)
{
int high[NUMS];
int low[NUMS];
int max = 40;
int min = -40;
printf ("---===IPC Temperatur Analyzer ===---\n");
printf ("Enter the high value for day 1: ");
scanf ("%d", &high);
printf ("Enter the low value for day 1: ");
scanf ("%d", &low);
while (high[0] > max || low[0] > min || high[0] < low[0]) {
printf("Try again\n");
printf ("Enter the high value for day 1: ");
scanf ("%d", &high[0]);
printf ("Enter the low value for day 1: ");
scanf ("%d", &low[0]);
}
printf ("Enter the high value for day 2: ");
scanf ("%d", &high[1]);
printf ("Enter the low value for day 2: ");
scanf ("%d", &low[1]);
printf ("Enter the high value for day 3: ");
scanf ("%d", &high[2]);
printf ("Enter the low value for day 3: ");
scanf ("%d", &low[2]);
return 0;
}
The high temperature for each day has to be greater than the low, the
high must not be greater than 41 and the low must not be less than
negative -41.
i have modified your code and written comment also to understand :
#include <stdio.h>
#define NUMS 3
int main (void)
{
int high[NUMS];
int low[NUMS];
const int MAX = 41;
const int MIN = -41;
printf ("---===IPC Temperatur Analyzer ===---\n");
printf ("Enter the high value for day 1: ");
scanf ("%d", &high[0]); //address of first element
printf ("Enter the low value for day 1: ");
scanf ("%d", &low[0]); //address of first element
/*Check for User Input Value*/
while (high[0] > MAX || low[0] < MIN || high[0] < low[0]) {
printf("Try again\n");
printf ("Enter the high value for day 1: ");
scanf ("%d", &high[0]);
printf ("Enter the low value for day 1: ");
scanf ("%d", &low[0]);
}
printf ("Enter the high value for day 2: ");
scanf ("%d", &high[1]);
printf ("Enter the low value for day 2: ");
scanf ("%d", &low[1]);
//TODO-:/*Check for User Input Value*/
printf ("Enter the high value for day 3: ");
scanf ("%d", &high[2]);
printf ("Enter the low value for day 3: ");
scanf ("%d", &low[2]);
//TODO-:/*Check for User Input Value*/
//TODO-:/*Print the all value*/
return 0;
}
Todo part you can complete by taking reference from other part of code.

Loop skips a scanf statement after the first time

Here is the code for main():
int main (void)
{
float acres[20];
float bushels[20];
float cost = 0;
float pricePerBushel = 0;
float totalAcres = 0;
char choice;
int counter = 0;
for(counter = 0; counter < 20; counter++)
{
printf("would you like to enter another farm? ");
scanf("%c", &choice);
if (choice == 'n')
{
printf("in break ");
break;
}
printf("enter the number of acres: ");
scanf("%f", &acres[counter]);
printf("enter the number of bushels: ");
scanf("%f", &bushels[counter]);
}
return 0;
}
Every time the program runs through the first scanf works fine but on the second pass through the loop the scanf to enter a character does not run.
Add a space before %c in scanf. This will allow scanf to skip any number of white spaces before reading choice.
scanf(" %c", &choice); is the only change required.
Adding an fflush(stdin); before scanf("%c", &choice); will also work. fflush call will flush the contents of input buffer, before reading the next input via scanf.
In case of scanf(" %c", &choice); even if there is only a single character in the input read buffer, scanf will interpret this character as a valid user input and proceed with execution. Incorrect usage of scanf may result in a series of strange bugs [like infinite loops when used inside while loop].

Resources