Subtracting in C adds and turns negative - c

I'm trying to make a simple calculator that asks how many numbers are needed (right now just for adding and subtracting) then collects those numbers for the user and does the corresponding math depending on what the user wants.
Here's my code:
if (option == 1) {
printf("ADDITION\n");
printf("How many numbers do you need? ");
scanf("%d", &n);
printf("Enter %d numbers:\n", n);
for(i=1; i<=n; i++){
scanf("%lf", &addNum);
sol = sol + addNum;
}
printf("Solution: %.2lf\n", sol);
}
if (option == 2) {
printf("SUBTRACTION\n");
printf("How many numbers do you need? ");
scanf("%d", &n);
printf("Enter %d numbers:\n", n);
for(i=1; i<=n; i++){
scanf("%lf", &subNum);
sol = sol - subNum;
}
printf("Solution: %.2lf\n", sol);
}
The addition works perfectly fine. The subtraction does not. I figured if adding is working, then replacing the + with an - would suffice but I guess not. The problem I'm having is, for example:
ADDITION
How many numbers do you need? 2
Enter 2 numbers:
10
5
Solution: 15.00
SUBTRACTION
How many numbers do you need? 2
Enter 2 numbers:
10
5
Solution: -15.00
Can someone help me understand how rather than subtracting, it's adding the numbers and going negative?

For subtraction (option 2) you have not assigned sol to be the value you wish to subtract from. In your code, you start subtracting from 0 straight away and therefore are left with a negative value.
A fix could be to say that for first number you want to subtract from, set it to be the value of sol.
for(i=1; i<=n; i++)
{
scanf("%lf", &subNum);
if(i == 1)
{
sol = subNum;
}
else
{
sol = sol - subNum;
}
}

Related

How to reset number to 0 after running program once again

I'm making program which converts sum of the numbers entered by user to binary, octal and hexadecimal. I would like to give a user an option to run program once again but with different numbers. Here is the problem - each time user repeats numbers, sum of these numbers are added to the previous entry. How do I stop incrementing? Is there any way to reset sum to 0? Thank you so much for your help!
Is there any way to reset sum to 0?
Yes, set sum to 0 right before the inner loop.
sum = 0;
while(1)
{
printf("Enter number: ");
scanf("%d", &value);
sum += value;
if(value == 0)break;
}
Also, rather then using while (1) with a break condition at the end, use a do..while loop.
sum = 0;
do {
printf("Enter number: ");
scanf("%d", &value);
sum += value;
} while (value != 0);
You would simply need to reset your sum variable to 0 if the user wants to reuse the number system with other numbers -
printf("\nEnter numbers once again? (y/n)\n");
scanf(" %c", &j);
printf("\n\nENTERING ONCE AGAIN\n");
if(j == 'n'||j == 'N')break;
***else sum = 0***

Imputing fractions using arrays in C

My program asks the user for a numerator and then a denominator right after (If option 1 is chosen). I am pretty sure i got that part correct.I can not seem to figure out how to display the fraction(s) though when I hit option 2.
This is my code:
#include<stdio.h>
#include<string.h>
typedef struct fraction
{
int numerator, denom;
} fraction; //defined the fraction.
int main()
{//start of program
int z = 0;
int y = 0;
while (1)
{ //start of while loop
int choice;
printf("\nPress 1 to enter a fraction\n");
printf("Press 2 to view the entered fraction\n");
scanf("%d", &choice);
fraction arrFraction[100];
arrFraction[0].numerator = 0;
arrFraction[0].denom = 0;
if (choice == 1) // first option (enter numerator and then denom after)
{
printf("Enter the fraction\n");
scanf("%d", &arrFraction[y].numerator);
scanf("%d", &arrFraction[z].denom);
y++
z++;
}// end of first if statement(to enter the fraction)
if (choice == 2) //to view the entered fractions.
{
printf("\n-----------------------------");
for (int m = 0; m < z; m++)
{
printf(" %d / %d \n", arrFraction[y].numerator/arrFraction[z].denom);
}
printf("\n\n-----------------------------");
} // end of second if statement (to view the fraction entered earlier)
} // end of while loop
system("pause");
return(0);
}
You need to move fraction arrFraction[100]; out of while loop, otherwise, every iteration, there will be a new array.
That said,
printf(" %d / %d \n", arrFraction[y].numerator/arrFraction[z].denom);
is wrong, you're supplying two format specifiers but one argument. This invokes undefined behavior. Your compiler should have warned you.
I believe, what you want instead is
printf(" %d / %d \n", arrFraction[y].numerator, arrFraction[z].denom);
That said, I'm not very convinced with the overall logic. Why do you seem to need an array of 100 elements? If you're only interested in previous record (not records), use only a simple variable, not an array. Besides, you don;t need to have two separate index/ counters anyway. A single index will be able to manage the inputs in much concise and robust way.

While loop to repeat a series of task multiple times in C program

I am writing a C program to repeat a series of question specified times. I ask user to enter the number of attempts they want and then I run the following while loop based on their number, but the problem is the loop keeps repeating. It does not stop at the specified number of attempt. Here is the code:
#include <stdio.h>
int main(void){
int num1,num2,high,low,average,subtotal,total_aver;
printf("Enter number of tries you want:");
scanf("%d", &num1);
while (num1 < num1 + 1) {
printf("Try number: ");
scanf("%d", &num2);
printf("Enter high ");
scanf("%d", &high);
printf("Enter low ");
scanf("%d", &low);
subtotal = high + low;
total_aver = subtotal / 2;
printf("Average temperature is: %d", total_aver);
}
}
If user enters 3 for number of tries then the program should ask those question in inside the loop three times, but it keeps repeating without ending.
while (num1 < num1 + 1) // condition is never false
Well this is infinite loop . It will continue and continue.
Write loop like this if you want to iterate number of times -
int i=0;
while(i<num1){
// your code
i++;
}
Or without any extra variable -
while(num1>0){
// your code
num1--;
}
This happens because the condition in the while is wrong.
Infact, assigning to num1 to any value, it will exit when num1 will be equal to num1+1. Is this impossibile, isn't it? You have to use another variable to take count of times you repeat the loop.
Fix this way:
int count=0;
while(count<num+1){
//your code
count=count+1;
}

Small c programming help needed

I have this problem I've been trying to get this done for last 7 hours, but I'm not getting anywhere. I have tried many options but I seem to fail all time. I'd be delighted if someone helped me out with this so I could see where I'm going wrong. I have made small attempt but the further I go to worst I get. I'd be happy if someone gave me some guidance please. Here is what the program should be like.
I have to enter integer numbers only if it's a floating number than it should display an error and that I need to try again. The minimum amount of numbers are 10.
Once all the numbers are entered it should display what the percentage of the numbers are even numbers.
At any time i can exit the program by typing "exit"
int i;
for(i=1; i<=10; ++i)
printf("Enter 10 integers: ");
scanf("%d",&i);
printf("Enter the next integer or type exit to end the program: %d",i);
system("PAUSE");
return (printf);
Since you asked for guidance rather than a full working solution, here goes.
First you currently have
for(i=1; i<=10; ++i)
printf("Enter 10 integers: ");
scanf("%d",&i);
The for will just loop around the next line, unless you use braces, i.e. it will print "Enter..." 10 times:
for(i=1; i<=10; ++i)
printf("Enter 10 integers: ");
scanf("%d",&i);
It may help to get used to putting everything you want to loop (even a one-liner) in braces:
for(i=1; i<=10; ++i)
{
printf("Enter 10 integers: ");
scanf("%d",&i);
//...
}
Often people (with good reason) start at 0 in C:
for(i=0; i<10; ++i)
{
printf("Enter 10 integers: ");
scanf("%d",&i);
//...
}
If you structure your code like that it may help to pull out a get_valid_input function
for(i=0; i<10; ++i)
{
printf("Enter 10 integers: ");
get_valid_input(); //what do you intend to do with this?
//...
}
with
int get_valid_input()
{
int i;
scanf("%d",&i); //how do they type "exit"?
//..
}
This needs thought though - should it return an int?
You could then store them somewhere.
But you could keep track of percentage of even numbers as you go.
Also, at any time you can press "exit" (type in the string or press a key?) so you need to be able to indicate that.
Don't forget to print the result, once you have worked it out. (Left as an exercise for the reader)
int i, v, n=0, even;
int array[10] = {0};
char buff1[32], buff2[32];
printf("Enter 10 integers: \n");
for(i=1; i<=10; ++i){
printf("Enter the next integer or type exit to end the program %d:\n", i);
fgets(buff1, sizeof buff1, stdin);
strcpy(buff2, strtok(buff1, " \t\n"));//trim
if(strcmp(buff2, "exit")==0)
break;
if(1!=sscanf(buff2, "%d%s", &v, buff1)){
printf("invalid input\n");
--i;
continue;
}
array[n++] = v;
}
for(even=i=0;i<n;++i){
printf("%d ", array[i]);
if((array[i] & 1) == 0)
++even;
}
printf("\n");
if(n)
printf("Even proportions : %.1f%%\n", 100.0*even / n);
system("PAUSE");
return 0;

calculating and finding difference in pairs of values in c

I really need help with this question.
Write a program that accepts six(6)
pairs of values from the user and then
calculates and stores the difference
of each pair of values in an array.The
array of calculated values should then
be sorted into ascending order and
printed on the screen.
I got through with inputting the six pairs of values, what I'm getting trouble with is the difference and storing in ascending order.
Any help given would be greatly appreciated.
#include <stdio.h>
main()
{
int arr[12], num1, num2, i;
for (i = 1; i < 7; i++) {
printf("Enter first number for pair ");
scanf("%d", &num1);
printf("Enter second number for pair ");
scanf("%d", &num2);
}
if (num1 > num2)
printf("arr[i-1=num1-num2 ");
else
printf("arr[i-1]=num2-num1 ");
{
for (i = 1; 1 < 7; i++)
printf("%7d\n", arr[i]);
}
return (0);
}
You need to check the difference immedialy after you read both values and store the value.
#include <stdio.h>
main()
{
int arr[7], num1, num2, i;
for (i = 0; i < 7; i++) {
printf("Enter first number for pair ");
scanf("%d", &num1);
printf("Enter second number for pair ");
scanf("%d", &num2);
//check differences now
if(num1>num2)
{
arr[i]=num1-num2;
}
else
{
arr[i]=num2-num1;
}
}
}
For the ordering of the vector, you could use a bubble-sort algorythm.
http://www.algorithmist.com/index.php/Bubble_sort.c
The reason for changing the vector and for limits is because vector positions go from 0 to n and not 1 to n, meaning that the for should go from 0 to 6 ( < 7 or <= 6 ).

Resources