Here is a code which evaluates the average of 10 entered numbers. Problem is it doesn't seem to print the sum correctly (it's always equal to 0) after exiting the loop, everything else is working fine.
int count=0, n=10, c;
float sum=0, x;
do{
printf("x=");
scanf("%f", &x);
count++;
sum+=x;
}
while(count<n);
printf("Sum is %d", sum);
printf("\nCount is: %d", count);
printf("\nThe Average of the numbers is : %0.2f", sum/count);
getch();
}
Another question is how to exit the loop after a symbol is reached(i.e. without setting a limit to the number of integers to be entered).
Use the %f format specifier for floating point numbers.
printf("Sum is %f", sum);
To exit the loop on a symbol, you could check the return value from scanf. scanf returns the number of items read. If it returns 0 then the user didn't type a valid number.
while (1) {
printf("x=");
if (scanf("%f", &x) != 1) {
break;
}
...
}
break exits the current loop.
To answer your first question it should be printf("%f",sum) to print the correct sum. Since you are using float you have to use %f, if you use int it is %d. For your second question, you can do something like this (modify it accordingly):
int main(){
// Declare Variables
int count = 0; float sum = 0, currentNum = 0;
// Ask user for input
while(currentNum > -1)
{
printf("Enter integer to be averaged (enter -1 to get avg):");
scanf("%f",¤tNum);
if(currentNum == -1)
break;
// Check the entered number and computed sum
printf("You entered: %0.2f\n", currentNum);
sum += currentNum;
printf("Current sum: %0.2f\n", sum);
count++;
}
// Print Average
printf("Average is: %0.2f\n", sum/count);
return 0;
}
To answer your second question, you could do this:
scanf("%f", &x);
if (x==0) {
break;
}
This will break you out of the loop if you enter 0, then your loop can be infinite:
do {
} while(true)
For the second question, I think EOF may be the better solution:
while(scanf("%f", &x) != EOF)
Related
I want this program to determine if given integers are positive/negative & odd/even then increment the counters. But it doesn't work properly.
include <stdio.h>
int main() {
int evenCount=0, oddCount=0, posCount=0, negCount=0, zeroCount=0, m;
char x='x';
while(x!='y') {
printf("enter an integer\n");
scanf("%d", &m);
if((m>0)&&(m%2==0)){
posCount+=1;
evenCount+=1;
}
else if((m>0)&&(m%2!=0)){
posCount+=1;
oddCount+=1;
}
else if((m<0)&&(m%2==0)){
negCount+=1;
evenCount+=1;
}
else if((m<0)&&(m%2!=0)){
oddCount+=1;
negCount+=1;
}
else {
zeroCount+=1;
}
printf("if you want to end the loop write 'y'\n");
scanf("%c", &x);
}
printf("odd %d \n", &oddCount);
printf("even %d \n", &evenCount);
printf("positive %d \n", &posCount);
printf("negative %d \n", &negCount);
return(0);
}
When I run it and give some numbers counts are at millions.
enter an integer
123
if you want to end the loop write 'y'
enter an integer
2
if you want to end the loop write 'y'
enter an integer
5
if you want to end the loop write 'y'
enter an integer
y
if you want to end the loop write 'y'
odd 6487572
even 6487576
positive 6487568
negative 6487564
The second example.
enter an integer
12
if you want to end the loop write 'y'
enter an integer
y
if you want to end the loop write 'y'
odd 6487572
even 6487576
positive 6487568
negative 6487564
I'm new to coding and this is my first post on this site also english is not my main language. I'm sorry if made any mistakes.
For starters you need to change this call
scanf("%c", &x);
to
scanf(" %c", &x);
Pay attention to the space before the conversion specifier.
And instead of trying to output addresses
printf("odd %d \n", &oddCount);
printf("even %d \n", &evenCount);
printf("positive %d \n", &posCount);
printf("negative %d \n", &negCount);
you have to write
printf("odd %d \n", oddCount);
printf("even %d \n", evenCount);
printf("positive %d \n", posCount);
printf("negative %d \n", negCount);
And it is better to substitute the while loop
while(x!='y') {
//...
printf("if you want to end the loop write 'y'\n");
scanf("%c", &x);
}
for do-while loop
do {
//...
x = '\0';
printf("if you want to end the loop write 'y'\n");
scanf(" %c", &x);
} while ( x != 'y' && x != 'Y' );
#include <stdio.h>
int main (void) //starting entry of integer indicate not associated with any data types argument
{
int value1, value2, calculate = 0; //integer values
printf ("\nProgram should perform the following:");
printf("\n");
printf ("\nHave the user enter two different integer numbers to be divided by the program ");
{
printf ("\nIf the division of both numbers");
printf("\n");
printf ("\nresult with the remainder of zero,");
printf("\n");
printf ("\nby the second number.");
printf("\n");
printf ("Example: thirty-five divided by seven will have a remainder of zero");
printf ("\n");
}
printf ("Please enter the first integer number>>");
scanf ("%i", &value1);
printf ("Please enter the second integer>> ");
scanf ("%i", &value2);
if (value1 % value2 == 0 ) {
printf ("\n%i is evenly divisible by %i\n", value1, value2);
calculate = value1 / value2;
printf ("%i / %i = %i\n", value1, value2, calculate);
else
printf ("\n%i is not evenly divisible by %i\n", value1, value2);
return 0;
}
This code, that I have written is working correctly. But I can't seem to find which else or else if statement to use to make the code say Error: A zero is allowed in the program if the second number that the user enters is zero.
If you want to introduce such message for the user, you have to implement the condition to check for the numbers after the user has provided the input. which can be done like:
#include <stdio.h>
int main(void) //starting entry of integer indicate not associated with any data types argument
{
int value1, value2, calculate = 0; //integer values
printf("\nProgram should perform the following:");
printf("\n");
printf("\nHave the user enter two different integer numbers to be divided by the program ");
printf("\nIf the division of both numbers");
printf("\n");
printf("\nresult with the remainder of zero,");
printf("\n");
printf("\nby the second number.");
printf("\n");
printf("Example: thirty-five divided by seven will have a remainder of zero");
printf("\n");
printf("Please enter the first integer number>>");
scanf("%i", &value1);
printf("Please enter the second integer>> ");
scanf("%i", &value2);
if (value1 == 0 && value2 != 0)
{
printf("\nA zero is allowed in the program if the second number that the user enters is zero");
return 0;
}
else
{
if (value1 % value2 == 0)
{
printf("\n%i is evenly divisible by %i\n", value1, value2);
calculate = value1 / value2;
printf("%i / %i = %i\n", value1, value2, calculate);
}
else
{
printf("\n%i is not evenly divisible by %i\n", value1, value2);
}
}
return 0;
}
Don't use parentheses after printf, it changes nothing and use %d inside scanf and printf for integers. And close if parentheses before else.
I need help fixing my code. What my code does it asking users to input a number multiple times and will terminate the program once -1 is entered. Then, will get the Sum, Max, Min, Average and Median values.
Sum, Min and Max seems to be working fine. But on the "Average" it's treating the -1 as a userinput, also, I need help on how to get the median value.
Here's what I got so far.
#include <stdio.h>
int main(){
char name[30];
int userInput;
int count = 0;
int sum = 0; // changed from 1 to 0
int max, min = 1000;
float average;
printf("Please enter your name: ");
scanf("%s", &name);
printf("Hello, %s, ", name);
do {
printf("Enter an integer (-1 to quit): ");
scanf("%d", &userInput);
if (userInput == -1) break; // I added this line, average works fine now
sum = sum + userInput;
count = count + 1;
average = sum / count;
if (userInput > max){
max = userInput;
}
if (userInput < min && userInput >= 0){
min = userInput;
}
}
while (userInput >= 0);
printf("Sum: %d \n", sum);
printf("Average: %.2f \n", average);
printf("Max: %d \n", max);
printf("Min: %d \n", min);
return 0;
}
Here's my sample output:
Please enter your name: A
Hello, A, Enter an integer (-1 to quit): 10
Enter an integer (-1 to quit): 20
Enter an integer (-1 to quit): 10
Enter an integer (-1 to quit): -1
Sum: 40
Average: 10.00
Max: 20
Min: 10
So The rest seems to be working now after some modification except for getting the median value.
You do not want to increment the count when userInput == -1
You're incrementing the count and adding to the sum before checking whether userInput == -1. Try rewriting your loop:
while(1){
printf("Enter an integer (-1 to quit): ");
scanf("%d", &userInput);
if(userInput == -1)
break;
/* rest of loop body goes here */
}
So, I am using xcode on mac and made a program that basically does simple math with the users entered values and keeps looping unless it is interrupted. At the end of the loop (once it is broken) I want to print out the total average value (so do some more math). I use a counter and sum variables to do this. However, in out output, I am getting a "nan" error when the loop end and the overall average has to display. Can anyone help, please? :/
int main() {
double gallons=0;
double miles=0;
double sum=0;
int count=0;
while (gallons>=0) {
sum+=(miles/gallons);
count++;
printf("\nEnter the gallons used (-1 to end): ");
scanf("%lf",&gallons);
if (gallons<0)
break;
printf("Enter the miles driven: ");
scanf("%lf",&miles);
if (miles<0)
break;
printf("The miles/gallon for this tank was: %lf", miles/gallons);
}
if (gallons<0) {
printf("The average is: %lf", sum/(count-1));
}
return 0;
}
double gallons=0;
double miles=0;
…
sum+=(miles/gallons);
Dividing zero by zero produces a NaN. Once there is a NaN, any arithmetic with it also produces a NaN.
Hm. In first iteration in sum+=(miles/gallons); you try to add to sum value 0/0. So, I think that you need to move this addition after inputs. Something like
printf("\nEnter the gallons used (-1 to end): ");
scanf("%lf",&gallons);
if (gallons<0)
break;
printf("Enter the miles driven: ");
scanf("%lf",&miles);
if (miles<0)
break;
printf("The miles/gallon for this tank was: %lf", miles/gallons);
sum+=(miles/gallons);
count++;
In my program I'm messing around with, it simply asks for how many tests one has written and then returns an average. However I've modified it a bit so that it asks if the marks entered are correct.
Problem 1: It doesn't let you input your marks for all your tests
Problem 2: If the marks are wrong it starts over but keep the previous inputs in it's memory? How do I fix the?
Here's the code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
//int variables for grade
unsigned int counter; //number of grades to be entered next
int grade;
int total;
float average;
// user input
int userInput; // amount of tests
int yesNo;
//amount of test passed
unsigned int pass = 0;
unsigned int fail = 0;
int doCount = 1;
//unsigned int test;
//---------------------------------------------------------------------------------------------------//
//standards for program to abide to
total = 0; //Total amount of test to be set to zero, until while statement
counter = 1; //Loop counter to start from one
//---------------------------------------------------------------------------------------------------//
printf ("Please enter amount of test you've written so far: ");
scanf ("%d", &userInput);
//printf ("%d", userInput);
//---------------------------------------------------------------------------------------------------//
do {
//Body of calculations of program
for(counter = 0; counter <= userInput; ++counter) { //for loop that correlates to userInput for amount of passes and test marks
printf ("Please enter percentage mark: "); //prompt for test mark
scanf("%d", &grade);
total = total + grade;
counter = counter + 1;
if (grade >= 40) { //if statement for pass or fail
pass = pass + 1;
} else {
fail = fail + 1;
}
}//end of for loop
printf ("Are the grades entered correct? (1 = yes, 2 = no): "); // user input for yesNo - are inputs correct
scanf ("%d", &yesNo);
if (yesNo == 2) {
} else {
average = ((float)total / userInput); //Getting average for tests so far
//if statement to clarify if you're passing
if (average < 40) {
printf ("\nYou are below sub minimum!\n");
printf ("Your overall average is: %.2f %\n", average);
printf ("Passed: %d\n", pass);
printf ("Failed: %d", fail);
} else if (average >= 75){
printf ("\nYou have a distinction agregate!\n");
printf ("Your overall average is: %.2f %\n", average);
printf ("Passed: %d\n", pass);
printf ("Failed: %d", fail);
} else {
printf ("\nYour overall average is: %.2f %\n", average);
printf ("Passed: %d\n", pass);
printf ("Failed: %d", fail);
}
doCount = 2;
}
} while (doCount == 1);
average = ((float)total / userInput); //Getting average for tests so far
//---------------------------------------------------------------------------------------------------//
getch ();
return 0;
}
In your do while loop, when you come around for your second pass you need to reset your variables. Specifically the total variable should be reset to zero. You do it for the first time outside the do while loop but once it's in the loop for the second pass it doesn't get reset to 0.
As for not reading all test inputs, if it asks for 9 but you need 10 then it likely is a problem with the for loop. I typically use counter++ and not ++counter as it increments the counter after the operation and not before the operation. That may or may not be the reason as I did not run your code, but it is worth looking at.
I've edited your code and commented the changes:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
//int variables for grade
unsigned int counter; //number of grades to be entered next
int grade;
int total;
float average;
// user input
int userInput; // amount of tests
int yesNo;
//amount of test passed
unsigned int pass = 0;
unsigned int fail = 0;
int doCount = 1;
//unsigned int test;
//---------------------------------------------------------------------------------------------------//
//standards for program to abide to
total = 0; //Total amount of test to be set to zero, until while statement
counter = 0; //Loop counter to start from zero, It's always better to start from zero
//---------------------------------------------------------------------------------------------------//
printf("Please enter amount of test you've written so far: ");
scanf("%d", &userInput);
//printf ("%d", userInput);
//---------------------------------------------------------------------------------------------------//
do {
//Body of calculations of program
total = 0; //You need to reset total pass and fail
pass = 0;
fail = 0;
for (counter = 0; counter < userInput; ++counter) { //for loop that correlates to userInput for amount of passes and test marks
printf("Please enter percentage mark: "); //prompt for test mark
scanf("%d", &grade);
total = total + grade;
//counter = counter + 1; You DON't need that
if (grade >= 40) { //if statement for pass or fail
pass = pass + 1;
}
else {
fail = fail + 1;
}
}//end of for loop
printf("Are the grades entered correct? (1 = yes, 2 = no): "); // user input for yesNo - are inputs correct
scanf("%d", &yesNo);
if (yesNo == 2) {
}
else {
average = ((float)total / userInput); //Getting average for tests so far
//if statement to clarify if you're passing
if (average < 40) {
printf("\nYou are below sub minimum!\n");
printf("Your overall average is: %.2f %\n", average);
printf("Passed: %d\n", pass);
printf("Failed: %d", fail);
}
else if (average >= 75) {
printf("\nYou have a distinction agregate!\n");
printf("Your overall average is: %.2f %\n", average);
printf("Passed: %d\n", pass);
printf("Failed: %d", fail);
}
else {
printf("\nYour overall average is: %.2f %\n", average);
printf("Passed: %d\n", pass);
printf("Failed: %d", fail);
}
doCount = 2;
}
} while (doCount == 1);
average = ((float)total / userInput); //Getting average for tests so far
//---------------------------------------------------------------------------------------------------//
getch();
return 0;
}