Reputation: 37
I've been trying to code for subtraction of numbers from n number to 0 (i mean in decrementing order like if n is 5 then 5-4-3-2-1-0) in C language. But I'm not getting the correct answer for that. Here's my code for that, please correct me wherever it is wrong.
#include<stdio.h>
int main(void) {
int i, n, sum;
printf("Enter any number:");
scanf("%d", &n);
for(i=n; i>=0; i--) {
sum -= i;
}
printf("%d\n", sum);
}
I have done the same code for addition of numbers from 0 to n numbers. I got that right, and according to that code I tried for the subtraction but wasn't getting the right answer. Please help me out, thank you.
Upvotes: 2
Views: 92
Reputation: 310980
The variable sum
was not initialized
int i, n, sum;
So it has an indeterminate value. As a result this statement
sum -= i;
invokes undefined behavior.
You need initially to set it to the entered value of the variable n.
Also as the variable n has the signed integer type int
then nothing prevents the user to enter a negative number. In this case the for loop will not be executed.
If I have understood correctly the assignment
i mean in decrementing order like if n is 5 then 5-4-3-2-1-0)
then your program can look the following way
#include<stdio.h>
int main(void)
{
printf( "Enter any number: " );
int n = 0;
scanf( "%d", &n );
int sum = n;
while ( n < 0 ? n++ : n-- ) sum -= n;
printf( "sum = %d\n", sum );
}
If to enter the number 5
then the output will be
Enter any number: 5
sum = -5
If to enter the number -5
then the output will be
Enter any number: -5
sum = 5
Upvotes: 4
Reputation: 67546
sum -= i
makes no sense as it makes sum 0 on the first iteration. Simply decrease the control variable.int main(void)
{
int start;
do
{
printf("\nEnter number:");
}while(scanf(" %d", &start) != 1);
printf("\n");
for(int current = start; current >= 0; current--)
printf("%d%s", current, current ? ", " : "\n");
}
https://godbolt.org/z/6bqnEr7nq
Upvotes: 0
Reputation: 523
First thing's first, you've got to initialize your variable sum. Furthermore - there is no need for the loop to iterate when i is 0, as it just subtracts 0 off the number. One last thing - you are missing a return statement for your main function. This code would do -
#include<stdio.h>
int main(void) {
int i, n, sum = 0;
printf("Enter any number: ");
scanf("%d", &n);
for(i = n; i > 0; i--) {
sum -= i;
}
printf("%d\n", sum);
return 0;
}
Upvotes: -1