-2

I am new into solving problems in programming,this is some problem from onlinejudge that i want to solve,

here is the problem :

you need to sum all of the inputs

sample input1:

1 -184

sample output1:

-184

sample input2 :

10 439 298 -935 72 636 774 -509 -568 228 47

sample output2 :

482

and here is my code :

main() {
int num,sum;
char ch;

while(ch != 10) {
   scanf("%d",&num);
   ch = getchar();

if(num != 1 || 0 ) {
    sum += num;
    }  
  }
  printf("%d",sum);
  return 0;
}

i am little bit lost here and wondering how to ignore those integer(1,0,10) my code worked on first sample,but not on the other one.

any solution?

Rach
  • 1
  • 1

2 Answers2

0

you have two options (among many others i'm certain)

  • Read individual numbers from the input (user types number, then hit enter/return); convert the string to number and if number is 1, 10 or 0, skip it and read the next number.
  • Read all the number in a string and use strtok to split the input in different numbers and convert the string to number and if number is 1, 10 or 0, skip it and read the next number.

look at this : How to get int from stdio in C?

look at this (and adapt to convert each string token to int (use something like strtol): How does strtok() split the string into tokens in C?

Max
  • 3,128
  • 1
  • 24
  • 24
0

you just need to initialize "sum" variable. it just works perfectly.

main() {
    int num,sum = 0;//Initalize Here
    char ch;

    while(ch != 10) {
       scanf("%d",&num);
       ch = getchar();

    if(num != 1 || 0 ) {
        sum += num;
        }  
      }
      printf("%d",sum);
      return 0;
    }
JDP
  • 56
  • 2
  • 10