Find the sum of all numbers entered - c

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;.

Related

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

Simple calculator using switch with if else in C

This is my code so far for my simple calculator. Im working on sine right now(case 6) with a degree range of 0-360.Here is the output.
$ ./a.exe ProblemSolving.c
Arithmetic : Add(0) Sub(1) Mult(2) Div(4) Mod(5)
Trigonometry : sine(6) cosine(7) tan(8) arc_sin(9) arc_cos(10)
Exponent : x^y(11) 2^x(12) 10^x(13)
Enter the choice of operation:6
The choice of operation is:6
Enter degree range from 0 to 360
Enter degrees:400
After I enter the desired degrees nothing else happens and the program ends. I believe there is something wrong with my if statement or the sine function.
#include <stdio.h>
#include <math.h>
int main() {
double Add1, Add2, Sub1, Sub2, Mult1, Mult2;
int Choice, Div1, Div2, Mod1, Mod2, Base1, Power1, Deg1;
printf("Arithmetic : Add(0) Sub(1) Mult(2) Div(4) Mod(5)\n");
printf("Trigonometry : sine(6) cosine(7) tan(8) arc_sin(9) arc_cos(10)\n");
printf("Exponent : x^y(11) 2^x(12) 10^x(13)\n");
printf("Enter the choice of operation:");
scanf("%d", &Choice);
printf("The choice of operation is:%d\n", Choice);
switch(Choice) {
case 0:
printf("Enter number one:");
scanf("%lf", &Add1);
printf("Enter number two:");
scanf("%lf", &Add2);
printf("%2.2lf + %2.2lf = %2.2lf", Add1, Add2, Add1+Add2);
break;
case 1:
printf("Enter number one:");
scanf("%lf", &Sub1);
printf("Enter number two:");
scanf("%lf", &Sub2);
printf("%2.2lf - %2.2lf = %2.2lf", Sub1, Sub2, Sub1-Sub2);
break;
case 2:
printf("Enter number one:");
scanf("%lf", &Mult1);
printf("Enter number two:");
scanf("%lf", &Mult2);
printf("%2.2lf * %2.2lf = %2.2lf", Mult1, Mult2, Mult1*Mult2);
break;
case 4:
printf("Enter number one:");
scanf("%d", &Div1);
printf("Enter number two:");
scanf("%d", &Div2);
if (Div2 == 0)
printf("Error! Denominator cannot equal 0");
else
printf("%d / %d = %d", Div1, Div2, Div1/Div2);
break;
case 5:
printf("Enter number one:");
scanf("%d", Mod1);
printf("Enter number two:");
scanf("%d", Mod2);
if (Mod2 == 0)
printf("Error! Denominator cannot equal 0");
else
printf("%d % %d = %d", Mod1, Mod2, Mod1%Mod2);
break;
case 6:
printf("Enter degree range from 0 to 360\n");
printf("Enter degrees:");
scanf("%d", Deg1);
if (0 > Deg1 > 360)
printf("Error! Value Entered is not within valid range");
else
printf("sin(%d) = %d", Deg1, sin(Deg1));
break;
default:
printf("Error! operator is not correct");
break;
}
return 0;
}
There are several problems in this code:
Change scanf("%d", Deg1); to scanf("%d", &Deg1);, because scanf() call for addresses. Also, I think it might be better to declare Deg1 as a double.
0 > Deg1 > 360 is wrong in C. You have to write Deg1 < 0 || Deg1 > 360. Operator || stands for "logical Or".
In math.h, sin() works in radians. So use sin(Deg1 * 3.14159265 / 180). Or, to improve readability and maintenance, #define PI 3.14159265 and sin(Deg1 * PI / 180). Note that you cannot write Deg1 / 180 * 3.14159265, because integer literals in C is ints, and int/int = int. For example, 3 / 2 == 1, rather than 1.5. To get the exact value, write 3.0 / 2.0.
In math.h, sin() returns double, so write printf("sin(%d) = %g", Deg1, sin(...));.
Fixed code here:
#include <stdio.h>
#include <math.h>
#define PI 3.14159265
// ...many lines of code...
case 6:
printf("Enter degree range from 0 to 360\n");
printf("Enter degrees:");
scanf("%d", &Deg1);
if (0 > Deg1 || Deg1 > 360)
printf("Error! Value Entered is not within valid range");
else
printf("sin(%d) = %g", Deg1, sin(Deg1 * PI / 180));
break;
The sine function (and the rest of the trig functions) in C works in radians, not degrees. You'll have to convert from degrees from radians before passing the value to sine.
Right now you also have a problem with the format in your printf, since you're passing a double, but telling printf to expect an int. You need to use %f instead of %d.
In addition, your if statement doesn't currently make much sense, and almost certainly doesn't mean what you think. What you apparently want is if (Deg1 < 0.0 || Deg1 > 360.0)

C program gives incorrect output?

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.

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