Sum of positive integers - Prints Garbage value
The program must accept N integers and print the sum S of all POSITIVE integers with the even positive integers reversed.
Example Input/Output 1:
Input: 4 39 -8 57 24
Output: 138
Explanation: The sum = 39+57+42 = 138 (The even number 24 is reversed)
Example Input/Output 2:
Input: 3 -23 -11 -445
Output: 0
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
|
#include<stdio.h>
#include <stdlib.h>
int main()
{
int n,i,arr[100000],count=0,rem,rev=0;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d ",&arr[i]);
}
for(i=0;i<n;i++)
{
if(arr[i]>0)
{
if(arr[i]%2==0)
{
while(arr[i]!=0)
{
rem=arr[i]%10;
rev=rev*10+rem;
arr[i]=arr[i]/10;
}
count=count+rev;
}
else
{
count=count+arr[i];
}
}
}
printf("%d",count);
}
|
The program runs perfect for the above two specified example i/o. But for
Input:
32
-89 90 -13 27 63 72 -17 33 58 73 -55 -46 -64 -65 87 62 -76 -13 -50 6 22 70 87 -39 -24 98 -31 -6 39 -80 46 -54
Output: -878418008
Explain me why the problem occurs and how to correct it.
Last edited on
Maybe the sum is too big and it overflows try using size_t for count instead
You don't reinitialise rev to 0 for each new positive even number. You just keep multiplying it by 10 until it overflows.
Set
rev=0;
between lines 19 and 20.
Topic archived. No new replies allowed.