C program gives incorrect output? - c

I am writing a C program which calculates average grade and tells if you pass or fail. The user can choose as many attempts as they want and they will be given a final average of all attempts. Here is my code:
#include <stdio.h>
int main(void)
{
int num1;
double num2, num3, average, average_1;
printf("Enter number of attempts: ");
scanf("%d", &num1);
while (num1 > 0) {
printf("Enter your mark for subject one: ");
scanf("%lf", &num2);
printf("Enter your mark for subject two: ");
scanf("%lf", &num3);
if (num2 < 50 || num3 < 50) {
printf("You have failed \n");
} else {
printf("You have passed \n");
}
num1--;
}
average = num1 * num2 * num3;
average_1 = average / 100;
printf("Average for all %d attempts is %.2f \n", num1, average_1);
}
The problem with this code is that the final output, which is the last printf line, gives me 0 for attempts and 0 for average. Here is the exact output:
Enter number of attempts: 2
Enter your mark for subject one: 49
Enter your mark for subject two: 96
You have failed
Enter your mark for subject one: 22
Enter your mark for subject two: 100
You have failed
Average for all 0 attempts is 0.00

You are dicrementing the variable num1. So, when you finish your loop you will have num1 = 0.
I suggest you do a 'for' instead of a 'while'. Like this:
#include <stdio.h>
int main(void) {
int num1, i;
double num2,num3,average,average_1;
printf("Enter number of attempts: ");
scanf("%d", &num1);
for(i = num1; i > 0; i--) {
printf("Enter your mark for subject one: ");
scanf("%lf", &num2);
printf("Enter your mark for subject two: ");
scanf("%lf", &num3);
if (num2 < 50 || num3 < 50) {
printf("You have failed \n");
}
else {
printf("You have passed \n");
}
}
average = num1*num2*num3;
average_1 = average / 100;
printf("Average for all %d attempts is %.2f \n", num1, average_1);
}

You have put the average calculation part in wrong place. Once you're out of the while loop, num1 will have a value 0, hence all the related calculations will return 0.

You are reducing num1 until it becomes 0
while (num1 > 0) {
// other code
num1--;
}
Then naturally
average = num1*num2*num3;
becomes
average = 0*num2*num3;
and that is 0

First, because you deduct num1 by one till 0.
You should use for loop:
for(int counter = num1; num1 > 0; num--)
{ Your code here }

Your loop will iterate until num1 is greater than 0 . As it decrement and become 0 program come out of loop but num1 has value 0 . Thus ,in these expressions num1 is 0-
average = num1*num2*num3; // 0*num2*num3 therefore , 0
average_1 = average / 100; // as average is 0 , thus result is 0
Also formula for calculating average_1 is wrong . It should be -
average_1=average/3; // you calculate average of 3 numbers
To get correct output create a temporary variable -
int i=num1;
while(i>0){
// your code
i--;
}
In this way num1 remain unchanged.

after the while loop, your num1 will be 0.

Related

Find the sum of all numbers entered

I need to read the number inputs from the user until they type in 0, print the sum of all entered number.
I am hoping to get this response:
Enter n: 50
Enter n: 25
Enter n: 10
Enter n: 0
total=85
So far my code is (sorry for my variables):
char ya;
float tem, ye, sum, roun=0.0;
printf("Enter n: ");
scanf("%f" ,&ye);
while (ye > 0 || tem > 0)
{
printf("Enter n: ");
scanf("%f", &tem);
roun = roun + tem;
}
sum = sum + ye;
printf("Total= %f\n", sum);
There are a few issues with the code you have shared. First of all for the code you have provided, you need to ensure temp is also initialised to 0. i.e temp=0
Then you already have some value in ye means the loop will not terminate. You once you are inside while loop, you need to reset the value of ye to 0. But before that you need to include the value of ye in the sum. So you will have to sum = sum + ye before the while loop.
Also in your code, you need to add round to sum and not ye.
So if I was to correct your code, it will look like below
tem=0;
printf("Enter n: ");
scanf("%f" ,&ye);
roun=ye;
while (ye > 0 || tem > 0)
{
printf("Enter n: ");
scanf("%f", &tem);
roun = roun + tem;
ye=0;
}
sum = sum + roun;
printf("Total= %f\n", sum);
but a better approach is to use do-while loops rather and have a code like below
do
{
printf("Enter n: ");
scanf("%f", &tem);
sum = sum + tem;
} while(tem>0);
printf("Total= %f\n", sum);
roun = roun + tem;
You add the values to roun, not sum. So noun should be the final value.
Then,
sum = sum + ye;
does not make sense. Because sum is uninitialized and it's value in indeterminate.
Aside: You can write sum += ye; instead of sum = sum + ye;.

Using C to Find Min and Max value using Function

I need to write a program where users can input their numbers as much as many as they defined, then the program will try to find which one is the lowest value and the highest value. The problems I face are:
When the program executed, the second line will wait on user's input (number) before the printf
The error "system" seems unreliable, sometimes works, sometimes doesn't work
The program only checks the last number entry, therefore it only shows the last number in min and max
You may give hints or corrections along the answers. Thank you very much.
#include <stdio.h>
float max(float num1){
float a=0, b;
if(num1 > a){
a=num1;
}
return a;
}
float min(float num2){
float x=100, y;
if(num2 < x ){
x=num2;
}
return num2;
}
int main(){
int times, interval;
float mini, maxi, data_Input;
printf("How many number would you like to type in ? : ");
scanf("%d\n",&times);
printf("Type in the number: ");
scanf("%f", &data_Input);
for(interval=2; interval<=times; interval++){
printf("\nType in the number: ");
scanf("%f",&data_Input);
while(data_Input<0){
printf("Invalid Input! Please re-enter the number:");
scanf("%f",&data_Input);
}
while(data_Input>100){
printf("Invalid Input! Please re-enter the number:");
scanf("%f",&data_Input);
}
}
maxi= max(data_Input);
mini= min(data_Input);
printf("The Lowest Number is %.2f\n", mini);
printf("The Highest Number is %.2f\n", maxi);
return 0;
}
Output:
How many number would you like to type in? : 5
70
Type in the number :
Type in the number : 90.7
Type in the number : 99
Type in the number : 30
Type in the number : 50
The Lowest Number is 50.00
The Highest Number is 50.00
Okay, the thing is that you are not updating the data_input after every successive number is inputted. What you are doing is, comparing the last number to 0 or 100, which is logically incorrect.
How about you take the first number as input, then after every successive input, compare it with the min and max value. Here is the sample code.
#include <stdio.h>
float max(float num1, float num2){
if(num1 > num2){
return num1;
}
return num2;
}
float min(float num1, float num2){
if(num1 < num2){
return num1;
}
return num2;
}
int main(){
int times, interval;
float mini, maxi, data_Input;
printf("How many number would you like to type in ? : ");
scanf("%d\n",&times);
printf("Type in the number: ");
scanf("%f", &data_Input);
// the first number will be minimum and maximum
mini = data_Input;
maxi = data_Input;
for(interval=2; interval<=times; interval++){
printf("\nType in the number: ");
scanf("%f",&data_Input);
// make it a composite if condition
while(data_Input<0 || data_Input>100){
printf("Invalid Input! Please re-enter the number:");
scanf("%f",&data_Input);
}
maxi= max(maxi, data_Input);
mini= min(mini, data_Input);
}
printf("The Lowest Number is %.2f\n", mini);
printf("The Highest Number is %.2f\n", maxi);
return 0;
}
The program checks the last number because you are calling the min and max function out of the for bracelets so instead you can call them inside the for bracelets like:
for(interval=2; interval<=times; interval++){
printf("\nType in the number: ");
scanf("%f",&data_Input);
while(data_Input<0){
printf("Invalid Input! Please re-enter the number:");
scanf("%f",&data_Input);
}
while(data_Input>100){
printf("Invalid Input! Please re-enter the number:");
scanf("%f",&data_Input);
}
maxi= max(data_Input);
mini= min(data_Input);
}
and instead of rewriting the same code you can just ask for the numbers inside the for loop and to initialize your interval to 1 so your main will look like:
int main(){
int times, interval;
float mini, maxi, data_Input;
printf("How many number would you like to type in ? : ");
scanf("%d\n",&times);
for(interval=1; interval<=times; interval++){
printf("\nType in the number: ");
scanf("%f",&data_Input);
while(data_Input<0){
printf("Invalid Input! Please re-enter the number:");
scanf("%f",&data_Input);
}
while(data_Input>100){
printf("Invalid Input! Please re-enter the number:");
scanf("%f",&data_Input);
}
maxi= max(data_Input);
mini= min(data_Input);
}
printf("The Lowest Number is %.2f\n", mini);
printf("The Highest Number is %.2f\n", maxi);
return 0;
}
Solving the printf issue is easy. As stdout is line buffered (at least by default - it can be changed) it is flushed whenever a newline is inserted in the buffer. So, just add a newline after each message print, for example
printf("How many number would you like to type in ? : \n");
and you'll be fine.
Talking about the wrong calculation of min and max, your attempt has basically two big issues:
You are not acquiring times inputs, but only one. In fact, every time you call scanf you overwrite the same variable data_Input without performing any comparison with the previous inputs
You call min() and max() function only once, after the last input. Furthermore you try to compare the argument with a local variable that has local storage and a lifetime limited to the function itself so that at the next call it will be initialized again
In order to have a variable inside a function that it is initialized only the first time you can use static keyword. But it is not I suggest you to solve the issue.
In my opinion you don't need comparison functions: you can just update maxi and mini each time you get a new input (solving both the aforementioned issues at once):
int main(){
int times, interval;
float mini, maxi, data_Input;
printf("How many number would you like to type in ? : \n");
scanf("%d",&times);
printf("Type in the number: ");
scanf("%f", &data_Input);
maxi = data_Input;
mini = data_Input;
for(interval=2; interval<=times; interval++){
printf("\nType in the number: \n");
scanf("%f",&data_Input);
while(data_Input<0){
printf("Invalid Input! Please re-enter the number:\n");
scanf("%f",&data_Input);
}
while(data_Input>100){
printf("Invalid Input! Please re-enter the number:\n");
scanf("%f",&data_Input);
}
/* Check input and, in case, update max and min */
if(data_Input > maxi)
maxi = data_Input;
if(data_Input < mini)
mini = data_Input;
}
printf("The Lowest Number is %.2f\n", mini);
printf("The Highest Number is %.2f\n", maxi);
return 0;
}
The comparison is performed inside the loop, so you don't need to store the inputs into an array.
You have plenty issues in your code.
Functions min & max do not make any sense
You do not check result of the scanf and you do not know if it was successfull
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define MIN(a, b) ((a) < (b) ? (a) : (b))
int main()
{
int times, interval;
float mini, maxi, data_Input;
do
{
printf("\nHow many number would you like to type in ? : ");
}while(scanf(" %d\n",&times) != 1);
for(interval = 0; interval < times; interval++)
{
do
{
printf("\nType in the number: ");
}while(scanf(" %f",&data_Input) != 1 && (data_Input < 0 || data_Input > 100));
printf("%f\n", data_Input);
maxi = interval == 0 ? data_Input : MAX(maxi, data_Input);
mini = interval == 0 ? data_Input : MIN(mini, data_Input);
}
printf("The Lowest Number is %.2f\n", mini);
printf("The Highest Number is %.2f\n", maxi);
return 0;
}
When the program executed, the second line will wait on user's input (number) before the printf
Drop "\n" from "%d\n". It blocks until non-white space detected after the number and is not needed.
printf("How many number would you like to type in ? : ");
// scanf("%d\n",&times);
scanf("%d",&times);
printf("Type in the number: ");
If output still not seen when expected, flush it. Typically printing a '\n' will flush stdout, but not certainly.
printf("How many number would you like to type in ? : ");
fflush(stdout); // add
The error "system" seems unreliable, sometimes works, sometimes doesn't work
At least this issue: sequential check vs. checking both conditions together input validity.
Rather than
while(data_Input<0){
...
}
while(data_Input>100){
...
}
Test together.
while(data_Input<0 || data_Input>100){
...
}
The program only checks the last number entry, therefore it only shows the last number in min and max
True as code only compares values once with one call to max(). That function only compares the number to 0 rather than prior values. Likewise for min().
Consider an algorithm change
// Pseudo code for max
prompt How many number would you like to type in ? : "
get times
max_value = -INF // set to minimum possible float
for each value 1 to times
prompt "Type in the number: "
get data_Input
if data_Input > max_value
max_value = data_Input
print max_value

C Programming - Getting the Median from User Inputs

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 */
}

How to create a loop without knowing when the loop will stop?

I am trying to create a program which takes a number and we match that number with a variable which has a specific number stored. We need to keep doing that until the user enters the correct number that matches the number we have stored in our variable:
#include <stdio.h>
int main(void) {
int i;
int j;
int num1;
int num2 = 2;
printf("Enter number");
scanf("%d", &num1);
while (num1 == 0) {
printf("Enter number");
scanf("%d", &num1);
}
while (num1 != num2) {
for(j=1;j
printf("This is not the correct number! \n");
printf("Enter number again: ");
scanf("%d", &num1);
}
if (num1 == num2) {
printf("The numbers have matched! \n");
}
}
I am confused with how do we create a loop where we don't know how many times the user will enter an incorrect number. What I want with the loop is to display
is how many times the user enters an incorrect number. Let say if they enter 3 times.
This is not the correct number 1!
This is not the correct number 2!
This is not the correct number 3!
But we don't know how many times the user will enter an incorrect number, so what condition do I put in a loop, so it counts.
You want to create a separate counter variable that keeps track of how many times you've gone through the loop. Set it to 0 before the loop, then increment on each iteration.
int count = 0;
...
while (num1 != num2) {
count++;
printf("This is not the correct number %d! \n", count);
printf("Enter number again: ");
scanf("%d", &num1);
}
Also, I'm presuming this is a typo:
for(j=1;j

Average of entered numbers in C - sum always 0

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",&currentNum);
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)

Resources