-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?

4
  • 3
    From the 2 inputs and outputs I cannot catch what is the algorithm. What do you want to ignore? Commented Jan 26, 2018 at 12:20
  • why do you want to not handle 1, 0 and 10 ? Commented Jan 26, 2018 at 12:21
  • you code work, I juste initialize the three variables at beginning Commented Jan 26, 2018 at 12:26
  • if(num != 1 || 0 ) is not doing what you think it is - the || 0 is a separate clause and always false Commented Jan 26, 2018 at 13:02

2 Answers 2

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?

Sign up to request clarification or add additional context in comments.

Comments

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;
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.