Umer February 2016

C error expected unqualified-id before 'if', 'else' and ' '{' token

I am writing a basic program in C++. I haven't programmed in C before, so I seem to be getting some fundamental errors. The program is a small quiz. Here it is:

#include <stdio.h>
int main(void)
int correct = 0

{
  int q1;
  printf("What is 24/(6-3)-7?\n ");
  scanf("%d",&q1)
}
{
  int q2;
  printf("What is -3x4+16?\n ");
  scanf("%d",&q12)
}{
  int q3;
  printf("What is 9²(1/27)?\n ");
  scanf("%d",&q1)
}

if(q1 == 1){
  correct == correct + 1
}
if(){
} else if 
if(q2 == 4){
  correct == correct + 1
}
if(q3 == 3){
  correct == correct + 1
}

Please bear in mind that I have composed this of bits and pieces picked off the internet. Any suggestions would be appreciated. Thank you

Answers


Barmar February 2016

  1. You need to put braces around the body of the function. And you shouldn't have braces around each block that asks a question -- that makes the variables like q1 local to that block, so you can't use them later in the function.

  2. Every statement must end with ;.

  3. if() is totally meaningless -- you have to put something inside the (); but I don't see the point of doing an extra check before checking the answer to question 2.

  4. To update correct, you have to use =, not ==; the latter is for comparison, not assignment. BTW, the idiomatic way to write correct = correct + 1 is correct++.

  5. Since main() is declared to return int, you should have a return statement at the end.

  6. You had a bunch of typos. For instance, you used &q12 and &q1 when you meant &q2 and &q3 in your scanf() calls.

#include <stdio.h>
int main(void) {
    int correct = 0;

    int q1;
    printf("What is 24/(6-3)-7?\n ");
    scanf("%d",&q1);

    int q2;
    printf("What is -3x4+16?\n ");
    scanf("%d",&q2);

    int q3;
    printf("What is 9^(1/2)?\n ");
    scanf("%d",&q3);

    if(q1 == 1){
        correct = correct + 1;
    }
    if(q2 == 4){
        correct = correct + 1;
    }
    if(q3 == 3){
        correct = correct + 1;
    }

    printf("You got %d answers correct!\n", correct);
    return 0;
}

Post Status

Asked in February 2016
Viewed 3,579 times
Voted 10
Answered 1 times

Search




Leave an answer