0

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

#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 perfectly 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 to me why the problem occurs and how to correct it.

always-a-learner
  • 3,671
  • 10
  • 41
  • 81

2 Answers2

3

You are not resetting rev = 0 for each new even number, hence the reversed values are wrong for even numbers.

if(arr[i]>0)
{  rev = 0;
    if(arr[i]%2==0)
Ramakanth Putta
  • 676
  • 4
  • 15
2

first of all try not to use extra space in scanf it will cause problem

for(i=0;i<n;i++){
scanf("%d",&arr[i]);}

then for your problem you forgot to make rev=0 thus it would have previous value and produce garbage result.

if(arr[i]%2==0)
    {
        rev=0;
        while(arr[i]!=0)
        {
            rem=arr[i]%10;
            rev=rev*10+rem;
            arr[i]=arr[i]/10;
        }
        count=count+rev;
    }

It will solve your issue.

Mohiuddin Sumon
  • 103
  • 2
  • 13