dimanche 1 août 2021

confused with K&R's 1.5.4 example

there while reading the K&R I got stuck at an example problem.

Here the aim of the program is to count the newlines, new words and the number of characters entered in the input. The code given in the book is :

#include <stdio.h>

#define IN 1
#define OUT 0

void main(){
    int c, nl, nw, nc, state;

    state = OUT;
    nl=nw=nc=0;
    while ((c = getchar()) != EOF)
    {
        ++nc;
        if (c == '\n')
            ++nl;
        if(c == ' ' || c == '\n' || c == '\t')
            state = OUT;
        else if(state == OUT){
            state = IN;
            ++nw;
        }  
    }
    printf("%d %d %d\n", nl, nw, nc);
    

}

  • It might look silly but sorry I'm new to C. I learnt that if the 'if' statement's condition gets true it simply doesn't check any other else if & else statements condition, only executes it's body and thus doesn't execute the bodies of other else & else if statements. But, in the code above (line:16) after checking the input with conditions of new word, it follows with an else if statement. And increments the nw in it's body. But how can else if gets executed if the if statement's condition is true.

non-numeric argument to binary operator with ifelse and apply

I hope nobody is getting (too) tired of me. I have given a completely fictional example of the problem below. The error is only given after including a mixture of numeric and string column in a data frame, even if the numeric columns are excluded from the function (not shown below). The function looks in column c for contents of d and vice-versa using grepl and then the should make a new column of the 'yes' and 'no' statements from ifelse. I need to ifelse to return the 'yes' and 'no' after the test but this is the part that is giving the error.

  a <- c(5:10)
  b <- c(105:110)
  c <- c("a","b","c","d","e","f")
  d <- c("aa","bc","cd","ff","ee", "gf")
  df <- data.frame(a,b,c,d)

  newfunction <- function(x, col1, col2, col3, col4){ifelse(((sapply(lapply(x[[col4]], grepl, 
  x[[col3]]),any)) | (sapply(lapply(x[[col3]], grepl, x[[col4]]),any))), (11 - x[[col1]]), (1 - 
  x[[col2]]))}
  df$new <- apply(df, 1, newfunction, "a", "b", "c", "d")
  
  Error in 11 - x[[col1]] : non-numeric argument to binary operator

How to stop if-statements conflicting each other? and how to make a program complete an if-statement before it does anything else?

I am creating a programme that uses DC motors to change gears on a bike. I have one DC motor for the rear set of gears ie 1-9 and I have a DC motor for the middle gears ie 1-3. The problem I have is that when I'm switching from gear 9 to gear 8, I press a button and the motor just keeps running forever.

This is my gear nine function:

void GearNine() {   //CHANGE FROM GEAR 9-10, or 10-9
  int target = 888;   // TARGET FOR GEAR 10

  // read the pushbutton input pin:
  buttonState = digitalRead(buttonPin);
  //  buttonState2 = digitalRead(buttonPin2);

  // compare the buttonState to its previous state
  if (buttonState != lastButtonState) {
    //if the state has changed, increment the counter
    if (buttonState == HIGH) {
      // if the current state is HIGH then the button went from off to on:
      
      //Turn on motor A
      MotorA_Forwards();
      MotorB_Backwards();
     }
  }
  if (pos >= 838) {   //GO TO GEAR 1 ON MOTOR 1
      MotorAOff();   //TURN MOTOR OFF
  }
  if (pos2 <= 50){   //GO TO GEAR 1 ON MOTOR 2
      MotorBOff();   //TURN MOTOR OFF
      buttonPushCounter2++; //ADD TO GEAR COUNTER
  }
  
  
  
//      delay(50);
  lastButtonState = buttonState;
    Serial.print(" Motor target: ");
    Serial.print(target);
    Serial.print(" pos1: ");
    Serial.print(pos);
    Serial.print(" pos2: ");
    Serial.print(pos2);
    Serial.print(" Gear: ");
    Serial.print(buttonPushCounter2);
    Serial.println();


        buttonState2 = digitalRead(buttonPin2);

  // compare the buttonState to its previous state
  if (buttonState2 != lastButtonState2) {
    //if the state has changed, increment the counter
    if (buttonState2 == HIGH) {
      
      // if the current state is HIGH then the button went from off to on:
      //Turn on motor B
      MotorB_Backwards();

      if (pos2 <= 7050) {   // WAS IN GEAR 9 BUT GO BACK TO GEAR 8
        MotorBOff();
        buttonPushCounter2--;  //MINUS 1 FROM GEAR COUNTER: WAS 9, NOW 8
      }
    }
  }
//  if (pos2 <= 7050) {   // WAS IN GEAR 2 BUT GO BACK TO GEAR 1
//  MotorBOff();
//  buttonPushCounter2--;  //MINUS 1 FROM GEAR COUNTER: WAS 2, NOW 1
//  }
  
  lastButtonState2 = buttonState2;
  lastButtonState = buttonState;
    
    Serial.print(" Motor target: ");
    Serial.print(target);
    Serial.print(" pos1: ");
    Serial.print(pos);
    Serial.print(" pos2: ");
    Serial.print(pos2);
    Serial.print(" Gear: ");
    Serial.print(buttonPushCounter2);
    Serial.println();

}

As you can see near the bottom I have these lines of code to make the gear run back down to gear 8 after the line of code that says MotorB_Backwards();:

if (pos2 <= 7050) {   // WAS IN GEAR 9 BUT GO BACK TO GEAR 8
        MotorBOff();
        buttonPushCounter2--;  //MINUS 1 FROM GEAR COUNTER: WAS 9, NOW 8
      }

If I have these lines of code here, the motor won't stop running if the button is pressed. Where as If I have the code where I have commented it out below these lines, then the if statement conflicts with this if statement which is slightly above in the code:

if (pos >= 838) {   //GO TO GEAR 2
      MotorAOff();   //TURN MOTOR OFF
  }
  if (pos2 <= 50){
      MotorBOff();
      buttonPushCounter2++;
  }

The reason it conflicts with these if statements is that if I want to go to gear 10. Motor A will go to pos 838 but motor B wont go down to pos2 of 50, instead it will stop at pos2 of 7050, because these if statements conflict with each other. So basically I'm not sure if my if statement is correct or if I'm putting it in the correct place or even wondering if there is a better way of doing this.

Maybe a simpler explanation/question would be how can I make an if statement complete what is within the if statement before it moves down the code. So I would like this if statement to be completed before it reads the next if statement:

if (pos >= 838) {   //GO TO GEAR 2
      MotorAOff();   //TURN MOTOR OFF
  }
  if (pos2 <= 50){
      MotorBOff();
      buttonPushCounter2++;
  } 

This is the if statement I don't want the program to run before its finished with the if statement above:

if (pos2 <= 7050) {   // WAS IN GEAR 9 BUT GO BACK TO GEAR 8
        MotorBOff();
        buttonPushCounter2--;  //MINUS 1 FROM GEAR COUNTER: WAS 9, NOW 8
      }

Much appreciated for anyone's help. Thank you.

is there any error in display function , any error in else if statements when i tried to compile there are no errors but output has only two zeroes?

Question

#include <stdlib.h>

struct Asteroid
{
    int size;
    struct Asteroid *next;
};

typedef struct Asteroid *NODE;

NODE push(NODE head,int data);
NODE pop(NODE head);
void display(NODE P,NODE N);

int main()
{
    NODE head=NULL;
    NODE P=NULL ;
    NODE N=NULL;
    int i,data,n;

    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
        scanf("%d",&data);
        P=push(head,data);

    }

    for(i=0;i<n;i++)
    {
        scanf("%d",&data);
        N=push(head,data);
    }

    display(P,N);
    return 0;

}

NODE push(NODE head,int data)
{
    NODE temp=(NODE)malloc(sizeof(struct Asteroid));
    if(temp==NULL)
    {
        exit(0);
    }
    temp->size=data;
    temp->next=head;
    head=temp;
    return head;
    }

NODE pop(NODE head)
{
    if(head==NULL)
    {
        printf("Stack is empty\n");
        return head;
    }
    NODE cur=head;
    head=head->next;
    free(cur);
    return head;
}


void display(NODE P,NODE N)
{
    int zero=0;
    int one=1;
    int count_coll=0;
    int count_noncoll=0;

    while(P!=NULL && N!=NULL)
    {
        if((P->size>0 && N->size>0) || (P->size<0 && N->size<0))
        {
            printf("%d\t",zero);
            P=pop(P);
            N=pop(N);
            count_noncoll++;
        }


        else if((P->size>0 && N->size<0) || (P->size<0 && N->size>0))
        {
            printf("%d\t",one);
            P=pop(P);
            N=pop(N);
            count_coll++;

        }



        else if(P->size==0)
        {
            P=pop(P);
        }

        else if(N->size==0)
        {
            N=pop(N);
        }
    }

    printf("%d\n",count_coll);
    printf("%d\n",count_noncoll);


}

this is the code part . The output part was to obtain zero if the asteroid(numbers)are of same sign and 1 if they are of opposite sign and to pop if zero appears. As you can see in the above image , the output as expected. But when i tried to run my program its showing no errors but the output is showing only " 0 0 ". i tried finding the errors but unable to figure out what is wrong. i think there is something wrong in the display function specifically the else if part . so please help me out with this.

samedi 31 juillet 2021

Python why does this lines cause an error? [closed]

Can someone explain the solution to project euler 68? I have found many code examples onlşne but still I can't undersand why we are doing what we are doing.

JS Question: How do I make my level 0 flow to level 1 in my chat prompt

I'm working on a message chat flow diagram where you input answers and it'll give you a reply working through the chart. However, I can't get my first level to connect with my second level. I can type in "name" and it will return correctly, but when I type in yes to answer then Do you like ice cream question. I get an undefined reply. Any help is greatly appreciated.

let level = 0;
let path;

const getReply = (userInput) => {
if (level === 0) {
level = 1;
if (userInput === "name") {
path = "name";
return "Hello, name. Do you have like ice cream?";
}
}


if (level === 1) {
level = 2;
if (path === "yes") {
if (userInput === "yes") {
  return "Great, what flavour do you like?";
 }
 }

How do I get if stamens to run in Java 11?

I am new to Java 11. I have a little experience with Java 8, but I am pretty much re-learning everything. I was trying to prompt for a Username and then password if the username was correct but Main won't run anything in the if statement. It asks for the username and then after typing the username whether wrong or right the program just ends. Cant figure this out. I tried changing variables and declaring them differently but I just started making it worse.This picture shows the code for my program