Goldi
Goldi

Reputation: 9

The for loop in C is not executed

The problem is my code doesn't execute the for loop. It's just taking one input and printing it.

#include<stdio.h>
        
int main(){
  int A[100], B[100], C[100], D[100];
  int r[100];
        
            
  for(int i = 0; i < 3; i++)
  {
      scanf("(%d+%d)x(%d-%d)", &A[i], &B[i], &C[i], &D[i]);
      r[i] = (A[i]+B[i])*(C[i]-D[i]);
  }
            
  for(int k = 0; k < 3; k++)
  {
      printf("%d", r[k]);
  }
        
  return 0;
}

Upvotes: 1

Views: 139

Answers (4)

Goldi
Goldi

Reputation: 9

i fixed it with Add a space before the first ( inside the scanf " (%d+%d)x(%d-%d)"

Upvotes: -1

chqrlie
chqrlie

Reputation: 145287

The problem is you do not skip the pending newline when reading the second line of input, so the newline does not match ( and scanf() returns 0.

You should always test scanf() return value to ensure input was validly converted.

Also make sure each result is printed as a separate number by appending a space or a newline.

Here is a modified version:

#include <stdio.h>
        
int main() {
    int A[100], B[100], C[100], D[100];
    int r[100];
    int n = 0;

    for (int i = 0; i < 3;) {
        /* ignore pending spaces */
        if (scanf(" (%d+%d)x(%d-%d)", &A[i], &B[i], &C[i], &D[i]) == 4) {
            r[i] = (A[i] + B[i]) * (C[i] - D[i]);
            n = ++i;
        } else {
            int c;
            /* flush pending input line */
            while ((c = getchar()) != EOF && c != '\n')
                continue;
            if (c == EOF)
                break;
            printf("Invalid input, try again:");
        }
    }
            
    for (int k = 0; k < n; k++) {
        printf("%d\n", r[k]);
    }

    return 0;
}

Upvotes: 0

August Karlstrom
August Karlstrom

Reputation: 11377

Assuming you input expressions are separated by a newline, when the second call to scanf is made, the first unread character is a newline rather than a left parenthesis. To make scanf skip leading whitespace characters, start the format string with a space, i.e. " (%d+%d)x(%d-%d)".

https://pubs.opengroup.org/onlinepubs/000095399/functions/fscanf.html

Upvotes: 3

Aditya kumar
Aditya kumar

Reputation: 96

First a fall this is the wrong way to use scanf.

use the below code:-

    #include<stdio.h>
    int main(){
    
    int A[100], B[100], C[100], D[100];
    int r[100];

    
    for(int i = 0; i < 3; i++)
    {
         scanf("%d %d %d %d", &A[i], &B[i], &C[i], &D[i]);
         r[i] = (A[i]+B[i])*(C[i]-D[i]);
    }
    
    for(int k = 0; k < 3; k++)
        printf("%d", r[k]);
    return 0;
}

Upvotes: 1

Related Questions