Reputation: 251
I have this piece of code, and I guess that it is pretty easy to understand what I am trying to do. However I get an error saying something like
the last else is called without an if before it.
I suspect that the problem is my if-else statement in between the if
and else
. How can I solve it?
int talet;
scanf("%d", &talet);
int i = 1;
while (i <= 99) {
int a; {
if (i % talet == 0 || talet == (i / 10) % 10 || talet == i % 10) {
if (talet % 10 == 0)
printf("\n");
else
continue;
}
printf("burr ");
else
printf("%d ", i);
}
i = i + 1;
}
Upvotes: 3
Views: 39215
Reputation: 113
try to keep your code-blocks as clean and readable as possible. This will prevent you from making mistakes.
You can write an if else Horstmann style:
if (condition)
{
#statements
}
else
{
#statements
}
or a bit more compact in TBS1 style:
if (condition) {
#statements
} else {
#statements
}
choose one you like, more styles in the comment provided by crashmstr (thanks to him), and stick to it. It WILL improve your code quality.
Upvotes: 1
Reputation: 1506
The problem is with your brackets. Indenting is important to understand where to open and close your brackets
int talet;
scanf("%d",&talet);
int i=1;
while(i<=99)
{
int a;
if (i%talet==0 || talet==(i/10)%10 ||talet==i%10)
{
if (talet%10==0)
printf("\n");
else
continue;
printf("burr ");
}
else
{
printf("%d ",i);
}
i=i+1;
}
Upvotes: 5
Reputation: 68440
The problem is that you have a printf
outside the if
brackets. Because of this, compiler thinks that the if
statement finished. When it reaches the else
, throws an error since there is no open if
condition
You should have this
if (i%talet==0 || talet==(i/10)%10 ||talet==i%10)
{
if (talet%10==0)
printf("\n");
else
continue;
printf("burr "); // <-- this was moved
}
else
printf("%d ",i);
Upvotes: 4
Reputation: 59701
Your problem is here:
}
printf("burr "); //<---
else
printf("%d ",i);
You can't have any statements before the else block. So remove it or move it inside the else OR if block, something like this:
} else {
printf("burr ");
printf("%d ",i);
}
Upvotes: 7